有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:获取类中的所有对象

我有一个类似这样的类:

public class Items {
    String uselessText;
    public static final Item COW = new Item("text", 0);
    public static final Item CAT = new Item("abc", 1);
    public static final Item DOG= new Item("wow", 2);
        ...SO on

    public void search(String search) {
          for(every Item in this Class) {
              if(item.textString == "abc") {
                 //DO SOMETHING
              }
          }

        }

这可能吗?不,谢谢,我不想做数组(因为我有100多个项目,我希望它们是静态访问)

有什么想法吗

干杯


共 (4) 个答案

  1. # 1 楼答案

    使用数组或列表。如果你担心超过100项的硬编码,那你就错了。从文本文件或其他文件中读取它们。但是,当您想要的是数组或列表的功能时,尝试使用一个新对象而不是数组或列表是没有意义的

  2. # 2 楼答案

    如果可以在编译时列出类的所有可能实例,use an ^{}

    public enum Items {
    
        COW("text", 0),
        CAT("abc", 1),
        DOG("wow", 2),
        // ...
        ;
    
        private final String textString;
        private final int number;
    
        private Item(String textString, int number) {
            this.textString = textString;
            this.number = number;
        }
    
        public void search(String search) {
            for(Item : values()) {
                if("abc".equals(item.textString)) {
                    //DO SOMETHING
                }
            }
        }
    }
    
  3. # 3 楼答案

    为什么不使用List<Item>?您可以将列表设置为static,尽管我不确定您为什么需要将其设置为static

    然后你可以做:

    for(Item item : items) {
        if("abc".equals(item.getTextString())) {
            //Do something
        }
    }
    

    请注意,不能使用==比较字符串(或任何对象);您必须使用.equals()。对于String,也可以使用.compareTo()。当使用==时,您只是在比较引用。另外,使用访问器,而不是在Itempublic上生成textString属性

  4. # 4 楼答案

    如果您不愿意使用数组,或者至少不愿意使用可移植的数组,那么您将使您的工作变得非常困难

    例如,下面是一些代码,它们将使用ArrayList<String>实现您想要的功能:

    public class Items {
        ArrayList<Item> itemSet = new ArrayList<Item>();
        // Code to fill in itemSet - involves itemSet.add(new Item("text", 0)), etc.
    
        public void search(String search) {
            for(Item i: itemSet) { // Enhanced for-loop, iterates over objects
                if ("abc".equals(i.textString)) {
                    // do something
                }
            }
        }
    }
    

    对这些对象进行静态访问是没有意义的。如果希望从该对象返回该数组,可以使用访问器将数组或ArrayList返回到需要它的任何对象