how to add multiple object on array list

时间:2015-10-29 15:44:58

标签: java object arraylist

I would like to add multiple objects to an ArrayList but I can't do it with my code. Here is the code I'm currently using. In the for loop, its adding the same object to the ArrayList 5 times. Why is this occurring?

import java.util.ArrayList;
import java.util.Scanner;
public class newBook {
    public int no;
    public String isim;

    public newBook(int no ,String isim){
        this.no = no;
        this.isim = isim;        
    }    
    @Override
    public String toString(){
        return " no = " + this.no +", name = " + this.isim;        
    }
    public static void main(String args[]){        
             Scanner klavye = new Scanner(System.in);
             int kitapNo = klavye.nextInt();
             String kitapName = klavye.next();            
             ArrayList<newBook> liste = new ArrayList<>();          
             for(int i=0 ; i<5 ; i++){               
                 liste.add( new newBook(kitapNo,kitapName));
                 //System.out.println("Çıkmak için -1 giriniz ");
                 //int i = klavye.nextInt();
             }             
        for (newBook liste1 : liste) {
            System.out.println(liste1);
        }             
    }
}

1 个答案:

答案 0 :(得分:4)

They are not the same object, they just have the same content. You need to read the input from klavye inside the loop too.