logo

Ustaw metodę add() w Javie z przykładami

Metoda add() zestawu w Javie służy do dodawania określonego elementu do kolekcji Set. Funkcja set add() dodaje element tylko wtedy, gdy określony element nie znajduje się jeszcze w zestawie, w przeciwnym razie funkcja zwraca wartość False, jeśli element jest już obecny w zestawie.

ile jest tam owoców

Deklaracja metody add().

boolean add (E element) Where, E is the type of element maintained by this Set collection.>

Parametry: Parametr element to typ elementu utrzymywany przez ten Zestaw i odnosi się do elementu, który ma zostać dodany do Zestawu.



Wartość zwracana: Funkcja zwraca True, jeśli elementu nie ma w zbiorze i jest nowy, w przeciwnym razie zwraca False, jeśli element już występuje w zbiorze. Poniższe programy ilustrują zastosowanie metody Java.util.Set.add():

Przykłady metody add() w Javie

Przykład 1

Jawa








// Java code to illustrate add() method> import> java.io.*;> import> java.util.*;> public> class> TreeSetDemo {> >public> static> void> main(String args[])> >{> >// Creating an empty Set> >Set s =>new> HashSet();> >// Use add() method to add elements into the Set> >s.add(>'Welcome'>);> >s.add(>'To'>);> >s.add(>'Geeks'>);> >s.add(>'4'>);> >s.add(>'Geeks'>);> >s.add(>'Set'>);> >// Displaying the Set> >System.out.println(>'Set: '> + s);> >}> }>

>

adnotacje dotyczące butów wiosennych

>

Wyjście

Set: [Set, 4, Geeks, Welcome, To]>

Przykład 2

Jawa




// Java code to illustrate add() method> import> java.io.*;> import> java.util.*;> public> class> TreeSetDemo {> >public> static> void> main(String args[])> >{> >// Creating an empty Set> >Set s =>new> HashSet();> >// Use add() method to add elements into the Set> >s.add(>10>);> >s.add(>20>);> >s.add(>30>);> >s.add(>40>);> >s.add(>50>);> >s.add(>60>);> >// Displaying the Set> >System.out.println(>'Set: '> + s);> >}> }>

>

jest tłuszcz białkowy

>

Wyjście

Set: [50, 20, 40, 10, 60, 30]>