C# IEnumerable Interface - ienumerable

I am trying to understand this example from a MSDN article, to my understanding with the IEnumberable interface, we will be able to use Foreach to loop through the class collection, I am confused at the Main method, why don't we just use:
foreach (Person p in peopleArray)
Console.WriteLine(p.firstName + " " + p.lastName);
instead of
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
Example:
using System;
using System.Collections;
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}

You're right, you could simply use the first version because arrays implement IEnumerable.
The reason they chose to iterate over People is simply for academic purposes; to demonstrate how iterators work (and how to implement IEnumerable). If they simply iterated over peoplearray, they wouldn't be using the People class, which is the main focus of that example.

Related

mybatis interceptor throw Reflection exception affects cpu performence

I had implement a interceptor of myabtis. but we found a problem, execute interceptor lead to throw so many IllegalAccessException, it affects cpu performence
Shown below is where the problem is, why did not check access permision of feild befor executed code "field.get(target)".
public class GetFieldInvoker implements Invoker {
private final Field field;
public GetFieldInvoker(Field field) {
this.field = field;
}
#Override
public Object invoke(Object target, Object[] args) throws IllegalAccessException {
try {
return field.get(target);
} catch (IllegalAccessException e) {
if (Reflector.canControlMemberAccessible()) {
field.setAccessible(true);
return field.get(target);
} else {
throw e;
}
}
}
#Override
public Class<?> getType() {
return field.getType();
}
}
the intercepor of mine:
#Intercepts({
#Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class})
})
public class SqlIdInterceptor implements Interceptor {
private static final int MAX_LEN = 256;
private final RoomboxLogger logger = RoomboxLogManager.getLogger();
#Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
String originalSql = boundSql.getSql();
MappedStatement mappedStatement =
(MappedStatement) metaObject.getValue("delegate.mappedStatement");
String id = mappedStatement.getId();
if (id != null) {
int len = id.length();
if (len > MAX_LEN) {
logger.warn("too long id", "id", id, "len", len);
}
}
String newSQL = "# " + id + "\n" + originalSql;
metaObject.setValue("delegate.boundSql.sql", newSQL);
return invocation.proceed();
}
#SuppressWarnings("unchecked")
public static <T> T realTarget(Object target) {
if (Proxy.isProxyClass(target.getClass())) {
MetaObject metaObject = SystemMetaObject.forObject(target);
return realTarget(metaObject.getValue("h.target"));
}
return (T) target;
}
}
Flame Graph
enter image description here
enter image description here
I need help, how to avoid throw exceptions, is any other way to reslove this problem?
thanks.

my area is not getting printed (abstract using interface)

I am currently new to interfaces and I encountered this problem regarding my getArea(), I would love if you guys can point out the error on my code
while this is my Triangle abstract class, I am not sure whether I putted the Semi-perimeter(sp) right or not:
private int sideA;
private int sideB;
private int sideC;
int sp = (sideA+sideB+sideC)/2;
double area = Math.sqrt(sp*(sp-sideA)*(sp-sideB)*(sp-sideC));
public Triangle() {
}
public Triangle(int sideA, int sideB, int sideC, int sp, double area) {
this.sideA=sideA;
this.sideB=sideB;
this.sideC=sideC;
}
public int getSideA() {
return sideA;
}
public void setSideA(int sideA) {
this.sideA = sideA;
}
public int getSideB() {
return sideB;
}
public void setSideB(int sideB) {
this.sideB = sideB;
}
public int getSideC() {
return sideC;
}
public void setSideC(int sideC) {
this.sideC = sideC;
}
public double getPerimeter() {
return sideA+sideB+sideC;
}
public double getArea() {
return getArea();
}
public void getDetails() {
System.out.println("\nType: Triangle" + "\nSides: " +this.sideA +", " +this.sideB+", "+this.sideC + "\nPerimeter: "
+ getPerimeter() + "\nArea: " + getArea() + "\ns: "+sp);
}
}```

Cannot access array of a custom class

In unity I keep getting the error message "NullReferenceException: Object reference not set to an instance of an object" on this:
listOfBanks[0].Deposit(50);
and
accntBlnce.text = "Account Balance:\n" + listOfBanks[curBank].GetBalance().ToString("c");
I have 3 options listed in the drop down menu and when I Debug.Log the number of items in the array I get 3 as my count. But I can't do anything with them. The banks variable is set as the Dropdown object in the inspector as well as the accntBlnce as the text object in my panel.
The code is below.
Banks.cs
public class Banks : MonoBehaviour {
public Dropdown banks;
public Text accntBlnce;
public Bank[] listOfBanks;
public int curBank = 0;
void Start() {
listOfBanks = new Bank[banks.options.Count];
listOfBanks[0].Deposit(50);
}
void Update() {
curBank = banks.value;
accntBlnce.text = "Account Balance:\n" + listOfBanks[curBank].GetBalance().ToString("c");
}
}
Bank.cs
public class Bank{
public Bank() { }
public Bank(string orgn, float amntToRprt, float blnce) {
origin = orgn;
amountToReport = amntToRprt;
balance = blnce;
}
public string origin { get; set; }
public float amountToReport { get; set; }
public float balance { get; set; }
public bool Deposit(float amnt) {
if (amnt > 0) {
balance += amnt;
if(amnt > amountToReport) {
FlagForReport();
}
return true;
}
else
return false;
}
private void FlagForReport() {
throw new NotImplementedException();
}
public float GetBalance() {
return balance;
}
public bool Withdraw(float amnt) {
if (amnt > 0) {
if (balance >= amnt) {
balance -= amnt;
return true;
}
else
return false;
}
else
return false;
}
public bool Transfer(float amnt, Bank bank) {
if (amnt > 0) {
if (balance >= amnt) {
if(bank.Deposit(amnt))
balance -= amnt;
return true;
}
else
return false;
}
else
return false;
}
}
This is the fourth time array question is asked this week with the-same problem and the-same solution.
You declared the array here:
listOfBanks = new Bank[banks.options.Count];
but you did not create new instance of each Bank script before calling
listOfBanks[0].Deposit(50); and listOfBanks[curBank].GetBalance().ToString("c").
Declaring array and setting the size is NOT the-same as creating new instance of a script.
The solution is to loop through the array and create new instance of each one.
In your Banks.cs, replace the code in your Start() function with the one below:
void Start()
{
//Declare how much Bank array should be created
listOfBanks = new Bank[banks.options.Count];
//Now Create instance of each bank
for (int i = 0; i < listOfBanks.Length; i++)
{
//Create new instance of each Bank class
//listOfBanks[i] = new Bank();
listOfBanks[i] = new Bank("", 50, 50);
}
listOfBanks[0].Deposit(50);
}

DataFlavor in JavaFX not recognized correctly

I'm experiencing a problem when D&D a custom object from Swing to JavaFX and I'm wondering if I'm doing something wrong or its probably a Java FX bug.
My Transferable has been defined as the following:
public class TransferableEmployee implements Transferable {
public static final DataFlavor EMPLOYEE_FLAVOR = new DataFlavor(Employee[].class, "Employee");
public static final DataFlavor DEFINITION_FLAVOR = new DataFlavor(PropertyDefinition[].class, "Definition");
private static final DataFlavor FFLAVORS [] = {EMPLOYEE_FLAVOR, DEFINITION_FLAVOR};
private Employee[] employees;
private PropertyDefinition[] propertyDefinitions;
public MintTransferableEmployee(Employee[] employees, PropertyDefinition[] propertyDefinitions) {
this.employees = employees != null ? employees.clone() : null;
this.propertyDefinitions = propertyDefinitions != null ? propertyDefinitions.clone() : null;
}
public DataFlavor[] getTransferDataFlavors() {
return FFLAVORS.clone();
}
public Object getTransferData(DataFlavor aFlavor) throws UnsupportedFlavorException {
Object returnObject = null;
if (aFlavor.equals(EMPLOYEE_FLAVOR)) {
returnObject = employees;
}
else if(aFlavor.equals(DEFINITION_FLAVOR)){
returnObject = propertyDefinitions;
}
else{
throw new UnsupportedFlavorException(aFlavor);
}
return returnObject;
}
public boolean isDataFlavorSupported(DataFlavor aFlavor) {
boolean lReturnValue = false;
for (int i=0, n=FFLAVORS.length; i<n; i++) {
if (aFlavor.equals(FFLAVORS[i])) {
lReturnValue = true;
break;
}
}
return lReturnValue;
}
}
I've created an imageView (FX Component) where I added the setOnDragOver just as the following:
employeePhotoImageView.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
System.out.println("dragOver");
event.getDragboard().getContentTypes();
event.getDragboard().getContent(DataFormat.lookupMimeType("application/x-java-serialized-object"));
}
});
The getContentTypes() returns a Map with [[application/x-java-serialized-object]], so now I try to get the Content, and this only returns the List of PropertyDefinition but no Employee at all (which in this case, is the one I need).
If I remove the data of the PropertyDefinition in the transferable, the employee is returned in the getContent(DataFormat) method.
For me, this means that JavaFX only works with 1 DataFlavor or somehow it is only returning the last flavor found in the Transferable.
Any clues on this?
Thanks in advanced...

Combo-box select item in JavaFX 2

I have one [JavaFX] ComboBox that is populated with countries.
My object:
public static class CountryObj {
private String TCountryDescr;
private String TCountryCode;
private CountryObj(String CountryDescr,String CountryCode) {
this.TCountryDescr = CountryDescr;
this.TCountryCode = CountryCode;
}
public String getTCountryCode() {
return TCountryCode;
}
public void setTCountryCode(String fComp) {
TCountryCode= fComp;
}
public String getTCountryDescr() {
return TCountryDescr;
}
public void setCountryDescr(String fdescr) {
TCountryDescr = fdescr;
}
#Override
public String toString() {
return TCountryDescr;
}
}
Then I have my ObservableList:
private final ObservableList<CountryObj> CountrycomboList =
FXCollections.observableArrayList(
new CountryObj("United States", "US"),
new CountryObj("United Kingdom", "UK"),
new CountryObj("France", "FR"),
new CountryObj("Germany", "DE"));
Then my ComboBox which displays the name of the country and the code of the country is for my own use:
private ComboBox<CountryObj> cCountry1 = new ComboBox<>();
cbCountry1.setItems(CountrycomboList);
cbCountry1.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<CountryObj>() {
#Override
public void changed(ObservableValue<? extends CountryObj> arg0, CountryObj arg1, CountryObj arg2) {
if (arg2 != null) {
System.out.println("Selected Country: " + arg2.getTCountryCode());
}
}
});
How can I auto-select a country, for example Germany, if I only have the code of the country, which is "DE"?
comboBox.getSelectionModel().select(indexOfItem);
or
comboBox.setValue("item1");
Couple of months old question but here is more elegant solution for such type of problems.
Modify the CountryObj class and override the hashCode and equals functions as below:
public class CountryObj {
private String TCountryDescr;
private String TCountryCode;
public CountryObj(String CountryDescr,String CountryCode) {
this.TCountryDescr = CountryDescr;
this.TCountryCode = CountryCode;
}
public String getTCountryCode() {
return TCountryCode;
}
public void setTCountryCode(String fComp) {
TCountryCode= fComp;
}
public String getTCountryDescr() {
return TCountryDescr;
}
public void setCountryDescr(String fdescr) {
TCountryDescr = fdescr;
}
#Override
public String toString() {
return TCountryDescr;
}
#Override
public int hashCode() {
int hash = 0;
hash += (TCountryCode != null ? TCountryCode.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
String otherTCountryCode = "";
if (object instanceof Country) {
otherTCountryCode = ((Country)object).TCountryCode;
} else if(object instanceof String){
otherTCountryCode = (String)object;
} else {
return false;
}
if ((this.TCountryCode == null && otherTCountryCode != null) || (this.TCountryCode != null && !this.TCountryCode.equals(otherTCountryCode))) {
return false;
}
return true;
}
}
Now in you code if you will execute the following statement, it will automatically select "Germany" for you.
cmbCountry.getSelectionModel().select("DE")
You can also pass an object of CountryObj to select method above.
I think the simplest solution is to write an autoSelect function that finds the matching CountryObj in your ObservableList. Once you find the correct CountryObj, tell the combobox to set that as its value. It should looks something like this...
private void autoSelectCountry(String countryCode)
{
for (CountryObj countryObj : countryComboList)
{
if (countryObj.getTCountryCode().equals(countryCode))
{
cbCountry1.setValue(countryObj);
}
}
}
EDIT:
This can be further refactored to reusable method for all ComboBox'es that take different type parameter:
public static <T> void autoSelectComboBoxValue(ComboBox<T> comboBox, String value, Func<T, String> f) {
for (T t : comboBox.getItems()) {
if (f.compare(t, value)) {
comboBox.setValue(t);
}
}
}
where Func is an interface:
public interface Func<T, V> {
boolean compare(T t, V v);
}
How to apply this method:
autoSelectComboBoxValue(comboBox, "Germany", (cmbProp, val) -> cmbProp.getNameOfCountry().equals(val));
If both comboBox are from the same Array, assembly column one and two, then they have the same sequence. Then you can use the index.
a = comboBox1.getSelectionModel().getSelectedIndex();
comboBox2.getSelectionModel().select(a);
"United States" is on index position 1 "US" also on index position 1 then:
comboBox2.getSelectionModel().select(1); // is "US"
The solution of Brendan and Branislav Lazic is perfect, but we still can improve the call to the autoSelectComboBoxValue method :
public static <T, V> void autoSelectComboBoxValue(ComboBox<T> comboBox, V value, Func<T, V> f) {...}
:)