简体   繁体   中英

HashSet doesnt allow duplicates but how to write logic for allowing duplicates

Consider the following program:

import java.util.*;

class SetDemo
{
    public static void main(String[] args)
    {
        Set s=new HashSet();

        s.add("ajay");
        s.add(120);
        s.add("A");
        s.add(120);
        System.out.println(s);
    }
}

It outputs [A,ajay,120] , but I want the output to contain 120 2 times. How can I achieve that?

You should use HashMap for key, value pairs. Or even a List. Sets by design only contain unique elements.

Write a list to add the values. It allows duplicates.

List s=new ArrayList(); 
s.add("ajay"); 
s.add(120);
 s.add("A");
 s.add(120); 
System.out.println(s); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM