2016-05-29 84 views
-2

我的程序将有很多的对象,将包含字符串,布尔值和其他,我想用ID调用它们。所以我想要这样的东西:Java - 使用名称形式的对象字符串字符串

int ID = 1; 
void add_object() 
{ 
String IDstring = Integer.toString(ID); 
myobject IDstring = new myobject(); 
ID++; 
} 

我应该如何使这工作?或者有没有更好的方法来做到这一点?

+1

你可以使用像'Map ' – pzaenger

+0

一致数据结构我从来没有听说过它,你能给我发送关于它的链接吗? – Stepik

+0

我不知道你在问什么。 –

回答

1

假设您有一个名为Foo的类。这个类可能是你的模式,这里存储所有字符串,布尔等:

public class Foo { 

    private final int id; 

    public Foo(int id) { 
     this.id = id; 
    } 

    @Override 
    public String toString() { 
     return this.getClass().getSimpleName() + "[id=" + id + "]"; 
    } 
} 

此外,您有另一个类的名称Bar,你有你的地图:

public class Bar { 

    private final Map<Integer, Foo> map; 

    public Bar() { 
     map = new HashMap<>(); 

     map.put(0, new Foo(0)); 
     map.put(5, new Foo(5)); 
     map.put(6, new Foo(6)); 
    } 

    private void list() { 
     System.out.println(map.get(0).toString()); 
     System.out.println(map.get(5).toString()); 
     System.out.println(map.get(6).toString()); 
    } 

    public static void main(String[] args) { 
     Bar bar = new Bar(); 
     bar.list(); 
    } 
} 

我有使用一致的id将三个对象添加到地图中。在list()内我打印这些对象。

我希望这可以帮助您开始。

看看这里阅读更多有关地图:public interface Map

编辑:当然,你可以使用一个字符串来存储ID。