Using a string to reference a custom class member of an array list
so I have a list 'Screens' which contains custom class objects of type 'screen' these are read from an XML file at run time. Also in the XML is a section called 'path' which contains strings, these are stored as further members of the 'screen' objects. What I'm trying to do is read the string value of path.left on the current screen and use to set the new value of currentScreen. ie. i know.. currentScreen.path.left = "park" so i want.. curr开发者_高级运维entScreen = currentChapter.Screens.park;
but it doesnt like it.. I tried the following but it wont find it in the list because the list is of 'screen's and not strings. Thanks.
String tmppath = currentScreen.path.left;
int index = currentChapter.Screens.indexOf(tmppath);
currentScreen = currentChapter.Screens.get(index);
the screen and path objects look like this:
public class Screen {
public String id;
public Integer backdrop;
public Paths path;
public List<Integer> areaMode = new ArrayList<Integer>();
public List<String> areaName = new ArrayList<String>();
public List<Region> areaArray = new ArrayList<Region>();
public Screen(String mid, Integer backDrop, Paths mpath, List<Integer> mareaMode ,List<String> mareaName, List<Region> mareaArray) {
id = mid;
backdrop = backDrop;
path = mpath;
areaMode = mareaMode;
areaName = mareaName;
areaArray = mareaArray;
}
}
public class Paths {
public String left;
public String right;
public String top;
public String bottom;
public Paths(String mleft, String mright, String mtop, String mbottom) {
left = mleft;
right = mright;
top = mtop;
bottom = mbottom;
}
}
Another problem i think I'm having is that I'm trying to find the 'Screen' instance using the 'id' string I've created inside of it.
The indexOf()
uses equals()
operation on your object to determine what the position of your object in the list is.
So, in your Screen object, the equals() method should use the path variable or some part of it for this to work. Without looking at that object, it would be hard to tell.
@Be77amy -- I'm going to make a wild assumption here that the path variable equates to the id of the Screen object. If that is true, then your problem is vastly simplified. You should implement a hashCode() and equals() method like so --
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Screen other = (Screen) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
This will also enable you to lookup by id.
Try using a Map instead of a List. A map allows you to store key-value pairs, so you can have a string key and your custom object for a value.
精彩评论