如何从ArrayList获取值

时间:2013-04-22 10:11:20

标签: java arraylist println

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class clsWarehouse {

private static int iChoice;
private int iItemID;
private String strItemName;
private String strItemDescription;
private int iItemPrice;
private String strSize;
private String strSex;


public clsWarehouse (int id, String name, String description, int price, String size, String sex){
    iItemID = id;
    strItemName = name;
    strItemDescription = description;
    iItemPrice = price;
    strSize = size;
    strSex = sex;   
}

public ArrayList <clsWarehouse> AllItems;
    public clsWarehouse(){
        AllItems = new ArrayList <clsWarehouse>();  
        AllItems.add(new clsWarehouse(3, "T-Shirt", "Male T-Shirt", 30, "15", "Male"));
        System.out.println(AllItems);
    }

public static void main(String[] args){
    clsWarehouse c = new clsWarehouse();
    }
}
 }

您好, 我想获取存储在ArrayList AllItems中的值,但我得到的只是内存位置[clsWarehouse @ a83b8a]。有人可以帮我这个。

谢谢!

3 个答案:

答案 0 :(得分:3)

您需要覆盖toString()课程中的clsWarehouseSystem.out.println在内部调用列表中对象的toString()。由于您没有在班级中覆盖toString()方法,因此您可以将以下内容作为输出。

getClass().getName() + '@' + Integer.toHexString(hashCode())

以上是Object类的toString()实现。

<强>更新: -

clsWarehouse课程中,添加以下方法。

public String toString(){
    return  "clsWarehouse"; //Modify this to return whatever you want to display in your sysout.
}

答案 1 :(得分:0)

您需要遍历数组列表才能获取值。还需要使用toString()将此人转换为字符串格式。然后,

 for (int i=0;i<AllItems .length();i++){
 //Then get the values one by one
 }

希望这会对你有所帮助。

答案 2 :(得分:0)

在clsWarehouse类中添加此方法

public String toString(){
    return  "iItemID: " + iItemID +" strItemName: "+ strItemName + " strItemDescription: "+ strItemDescription +" iItemPrice  "+ iItemPrice: + " strSize: " + strSize + " strSex: "+strSex; 
}

更改此

System.out.println(AllItems);

for(clsWarehouse item : AllItems){
     System.out.println(item.toString());
}