Вопрос

I'm studying Collections right now and from what i learned i saw that Set is a type of collection that don't permit duplicate elements. Ok, i've created a class what adds three int numbers to a collection. It seems ok but the question is: how could i print this collection? I know that i could override the String method but since my elements is integer type how could i do that? My expected output would be: 2,3,2 4,5,6

The code (Adding numbers)

public class adaugareNumere {
int c=0;
int f=0;
int r=0;

adaugareNumere(int c, int f, int r){
this.c=c;
this.f=f;
this.r=r;
}


}

Main class:

import java.util.*;
public class Executare {



public static void main(String[] args) {
    adaugareNumere primulRand=new adaugareNumere(2,3,2);
    adaugareNumere alDoileaRand=new adaugareNumere(2,3,2);
    adaugareNumere alTreileaRand=new adaugareNumere(4,5,6);
    Set<adaugareNumere> lista=new HashSet<adaugareNumere>();
    lista.add(primulRand);
    lista.add(alDoileaRand);
    lista.add(alTreileaRand);
    System.out.println("Elementele listei: "+Arrays.asList(lista.toString()));

}

}
Это было полезно?

Решение

You need to override the toString() method in your adaugareNumere class.

Example:

@Override
public String toString() {
    return "adaugareNumere [c=" + c + ", f=" + f + ", r=" + r + "]";
}

And just give the list in the SOP statement.

System.out.println("Elementele listei: " + lista); // No need for `Arrays.asList()` or `toString()`.

Другие советы

To retrive Value from Set. Iterator could be used :

Iterator itr    =   lista.iterator();
while(itr.hasNext()){
        System.out.print(itr.next()+",");
    }

But Since you are trying to put Object in Set, the duplicate object will not be permitted but values can be duplicate

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top