darkaziz
darkaziz

Reputation: 3

How to remove element in a certain set which is stored in Arraylist of Set in JAVA?

I have a problem on removing an element in a certain set which is stored in Arraylist of Set in JAVA.

My code is like this :

public class Classroom {

    private ArrayList<Set<Integer>> arrSetSlot;
    private Set<Integer> SetSlot;

    public Classrom(){
        arrSetSlot = new ArrayList();
    }

    public ArrayList<Set<Integer>> getHimpWaktu_tersedia() {
        return arrSetSlot;
    }

    public void addSlotWaktu(int kromosom, int Slot){
        arrSetSlot.get(kromosom).add(Slot);
    }    

    public void addSlotWaktu(Set<Integer> SetSlot){
        arrSetSlot.add(SetSlot);
    }
}


public class Inisialisasi {
    ArrayList<Classrom> arrClassroom;
    Set<Integer> SetSlot;
    Database d;

    public Inisialisasi(){
        arrClassroom=new ArrayList();
        SetSlot=new HashSet();
        d = new Database();
        loadDatabase();
        validasiData();
    }

    private void loadDatabase(){
        for (int i=1;i<41;i++){
            SetSlot.add(i);
        }

        rs=d.getData("select* from kelas");
        try {
            while(rs.next()){
                Classroom kelas = new Classroom();
                kelas.setIdKelas(rs.getString("id_kelas"));
                kelas.setKodeKelas(rs.getString("kode_kelas"));
                for(int i=0;i<3;i++){
                    kelas.addSlotWaktu(SetSlot);
                }
                arrKelas.add(kelas);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Inisialisasi.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void validasiData(){
        //the problematic remove
        arrKelas.get(2).getHimpWaktu_tersedia().get(2).remove(1);
        for (int i=0;i<arrKelas.get(1).getHimpWaktu_tersedia().size();i++){
            System.out.println(arrKelas.get(1).getHimpWaktu_tersedia().get(i).size());
        }
    }
}

When I tried to remove elements from certain set in the array using this function : classroom.getArrSetSlot.get(1).remove(1);

It was not only removing the element "1" from the first set but also removing element "1" from all sets in the arraylist..

Any solution for this problem?? Thanks

Upvotes: 0

Views: 205

Answers (2)

trutheality
trutheality

Reputation: 23465

Well,

public void addSlotWaktu(Set<Integer> SetSlot){
    arrSetSlot.add(SetSlot);
}

should probably be

public void addSlotWaktu(Set<Integer> SetSlot){
    arrSetSlot.add(new HashSet<Integer>(SetSlot));
}

assuming that you want a new independent copy of that set in the slot.

Upvotes: 3

Ram&#243;n
Ram&#243;n

Reputation: 21

Try this:

arrSetSlot = new ArrayList<Set<Integer>>();

Upvotes: 0

Related Questions