www

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
q1:

1-using an array for exapmle:

Set<String> GFG = new HashSet<String>();

GFG.add("Welcome");
GFG.add("To");
GFG.add("Geeks");
GFG.add("For");
GFG.add("Geek");

String[] Geeks = GFG.toArray(new String[GFG.size()]);

System.out.println("Element at index 3 is: " + Geeks[3]);
-----------------------------------------------------------------------------------

2-using a for each loop for exapmle:

Set<String> set = new HashSet<>();

set.add("apple");

set.add("banana");

set.add("orange");



for (String element : set) {

    System.out.println(element);

}

-------------------------------------------------------

3-using an array list for exapmle:

ArrayList<String> list = new ArrayList<>();

list.add("apple");

list.add("banana");

list.add("orange");



String element = list.get(1); // retrieves the second element ("banana")

System.out.println(element);

4-using an iterator for exapmle:

Set<String> set = new HashSet<>();

set.add("apple");

set.add("banana");

set.add("orange");



Iterator<String> iterator = set.iterator();

while (iterator.hasNext()) {

    String element = iterator.next();

    System.out.println(element);

}

----------------------------------------------------------

q2-iterator and lists gives you more control over the iteration process. For example, you can remove elements from the set while iterating over it using an iterator so i using them

they also provide additional methods such as hasPrevious() and previous() for iterating over the elements in reverse order.

-------------------------------------------------------

q3-Set does not provide a method to get an element by index, because the order of elements in a Set is not defined