如何从对象数组中打印出一个元素

时间:2017-09-10 14:26:01

标签: java arrays printing

我试图从对象数组中打印出一个对象,该数组包含5个对象,我问的是如何只打印其中一个对象,例如store [1]?

public static void main(String args[]){
    Customer[] store = new Customer[5];
    Customer c = new Customer(1, "Szabi", "Master");
    Console console = new Console();
    store[0] = new Customer(1, "Szabi", "Finchley");
    store[1] = new Customer(2,"Anca", "Finchley") ;
    store[2] = new Customer (3, "Deniz","Cricklewood");
    store[3] = new Customer(4,"Suzanna", "Cricklewood") ;
    store[4] = new Customer (5, "Lavinia", "Ealing");


    //How do I print out just store[0] or just store[1]?
}

我无法在某个索引处打印出来,例如store [1]或store [0],因为无论我放在方括号中,它总是会打印出商店[4]的值。 客户类如下:

package Eldorado;

 import java.util.Arrays;

public class Customer implements CustomerItem , Comparable<Customer> {
static int id;
static String name;
static String address;


public Customer(){
id=0;
name=null;
address=null;
}
public Customer(int _id, String _name, String _address){
this.id=_id;
this.name=_name;
this.address=_address;
}
 public void setId(int _id){
this.id=_id;
}
public void setName(String _name){
this.name=_name;
}
public void setAddress(String _address){
this.address=_address;
}
 @Override
 public int getId(){
return id;
}@Override
public String getName(){
return name;
}@Override
public String getAddress(){
return address;
}@Override
public boolean equals(CustomerItem other){
Customer a = new Customer();
Customer b = new Customer();
if(a.compareTo(b)==0){
    return true;
}else{
    return false;
}
}@Override
public int compareTo(Customer that){
if(this.id==that.id&&this.name==that.name&&this.address==that.address){
    return 0;
}else if(this.id>that.id){
return 1;
}else{
return -1;
 }
}
@Override
public String toString(){
return Integer.toString(getId())+getName()+getAddress();
}
}

1 个答案:

答案 0 :(得分:3)

使用此System.out.println(store[0]); 但是,您应该覆盖toString方法以从对象打印您想要的内容,因为Object类继承的默认方法不会为您的应用程序打印非常有用的信息,我想。