Reputation: 25
One of the questions I have been given asks:
All the lines should be stored in an object of type
List<Set<Integer>>
.
How do you write this in Java, as in how do you initialise this list? I've never seen this before.
Please provide a link to an explanation as i'm not sure what this is called in Java so have no idea about how to learn about it. Thank You.
Upvotes: 1
Views: 12813
Reputation: 8021
Its a List of Sets where each Set can hold only Integers.
Set<Integer> singlesSet = new HashSet<>();
singlesSet.add(1);
singlesSet.add(2);
Set<Integer> tensSet = new HashSet<>();
tensSet.add(10);
tensSet.add(20);
List<Set<Integer>> list = new ArrayList<>();
list.add(singlesSet);
list.add(tensSet);
System.out.println(list);
Upvotes: 5
Reputation: 1677
In Java, the List
interface represents an abstract list of things. Any class the implements List
(for example, LinkedList
) must implement its methods and behave according to its contract.
You can essentially think of it as an array, but keep in mind that arrays are only one kind of list, and that implementations of List
do no have to use arrays internally.
The Set
also represents a collection of elements, but with no relationship or connection between them. Visually, you can think of a set as a sort of bag of things. You can add and remove things from the bag, but none of the items need to be related.
An Integer
, of course, is just an object wrapper around Java's int
primitive.
As such, a List<Set<Integer>>
object would be similar to a two-dimensional array, only without a defined order in the second dimension.
You would initialize a List<Set<Integer>>
as follows:
List<Set<Integer>> myList = new ArrayList<HashSet<Integer>>();
Where ArrayList
and HashSet
can be any classes that implement List
and Set
, respectively.
Upvotes: 0
Reputation: 1854
The short way:
List<Set<Integer>> list = new ArrayList<Set<Integer>>();
Set<Integer> set = new HashSet<Integer>();
list.add(set);
set.add(1);
set.add(2);
....
What is the difference between Set and List?
Upvotes: 0
Reputation: 3568
Like this List<Set<Integer>> yourList = new ArrayList<Set<Integer>>();
?
You may want to take a look at https://docs.oracle.com/javase/7/docs/api/java/util/List.html
Upvotes: 0
Reputation: 3640
Example of usages of Set
and List
. Note that elements in a TreeSet
are always sorted.
List<Set<Integer>> listofsets = new ArrayList<Set<Integer>>();
Set<Integer> set1 = new TreeSet<Integer>();
set1.add(1);
set1.add(2);
Set<Integer> set2 = new TreeSet<Integer>();
set2.add(6);
set2.add(4);
listofsets.add(set);
// listofsets = {{1,2}, {4,6}}
Upvotes: 3