[英]Java array with multiple values
I want to create a multidimensional array where each of the nodes will have the following details: 我想创建一个多维数组,其中每个节点将具有以下详细信息:
Which is the best way to do this when I have over 30 values ? 当我有超过30个值时,哪种方法最好?
Example: 例:
"Bangalore", "200", "city" “班加罗尔”,“200”,“城市”
"Mysore", "100", "historic" “迈索尔”,“100”,“历史性”
I am trying to populate a list array in Android where each row has three details - name, icon, distance so I want to temp populate that data in my java class. 我试图在Android中填充一个列表数组,其中每行有三个细节 - 名称,图标,距离,所以我想临时填充我的java类中的数据。
Don't use a multidimensional array. 不要使用多维数组。 Use a simple array (or List) of objects: 使用简单的对象数组(或List):
public class Place {
private String name;
private String icon;
private int distance;
// constructor, methods skipped for brevity
}
...
private Place[] places = new Place[10];
// or
private List<Place> places = new ArrayList<Place>();
Java is an OO language. Java是一种OO语言。 Learn to define and use objects. 学习定义和使用对象。
I think best option is create custom defined object. 我认为最好的选择是创建自定义对象。
Class TestObject
{
String Place,Icon,Distance;
// Setter and Getter method
}
// Create object of class. Store your value using setter and getter method
and save object into list
List<TestObject> test = new ArrayList<TestObject>();
test.add(testObject); //
Create a class with the attributes that you want in an element. 使用元素中所需的属性创建一个类。
now you can create an array of objects of this class. 现在您可以创建此类的对象数组。
class Place {
private String name;
private String icon;
private int distance;
public Place(String name,String icon,int distance){
this.name=name;
this.icon=icon;
this.distance=distance;
}
} }
Place places[]=new Place[10];
places[0]=new Place("Mysore","wildlife",123);
and so on
beware of instantiating the objects else you will endup getting NullPointerException 要小心实例化对象,否则你最终会得到NullPointerException
If you don't want to create a separate class . 如果您不想创建单独的类。 You can also use JSON for your purpose. 您也可以将JSON用于您的目的。
JSON object is light weight and can manage aaray data very easily. JSON对象重量轻,可以非常容易地管理aaray数据。
Like : 喜欢 :
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
ja.put("Mysore");
ja.put("wildlife");
ja.put(123);
jo.add(KEY, ja); // Adding array to JSON Object with key [KEY can be any unique value]
JSON are easy to read and manageable. JSON易于阅读和管理。
It provides lots of functionality rather than array. 它提供了许多功能而不是数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.