我有对象(元素)的数组列表,需要查找具有不同样式的所有元素:
ArrayList<Element> = new ArrayList<Element>();
class Element {
String text;
Style style;
public Element() {}
}
class Style {
String background;
Integer size;
public Style() {}
}
最佳答案
ArrayList<Element> list = new ArrayList<>();
// define elements:
Element e1 = new Element();
e1.setText("1. Element");
e1.setStyle(new Style("#343434", 100));
Element e2 = new Element();
e2.setText("2. Element");
e2.setStyle(new Style("#343411", 100));
Element e3 = new Element();
e3.setText("3. Element");
e3.setStyle(new Style("#343434", 101));
Element e4 = new Element();
e4.setText("4. Element");
e4.setStyle(new Style("#343434", 100));
// add elements to list:
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);
// define standard stayl and size
String backgroundStandard = "#343434";
Integer sizeStandard = 100;
// check elements
for(int i=0; i<list.size(); i++){
if(!list.get(i).getStyle().getBackground().equals(backgroundStandard)){
System.out.println(list.get(i).getText() + " has a different background!");
}
if(list.get(i).getStyle().getSize() != sizeStandard){
System.out.println(list.get(i).getText() + " has a different size!");
}
}
class Element {
String text;
Style style;
public Element() {}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Style getStyle() {
return style;
}
public void setStyle(Style style) {
this.style = style;
}
}
class Style {
String background;
Integer size;
public Style(String background, Integer size) {
this.background = background;
this.size = size;
}
public String getBackground() {
return background;
}
public void setBackground(String background) {
this.background = background;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
}
关于java - 对象的Arraylist查找所有不同属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60809934/