Created
September 5, 2016 12:21
-
-
Save vslala/84ea1cfad848f70ea225043ba76900b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.ArrayList; | |
| import java.util.HashMap; | |
| import java.util.HashSet; | |
| import java.util.Iterator; | |
| import java.util.List; | |
| import java.util.Map; | |
| import java.util.Set; | |
| class CollectionExample { | |
| // Lets start collection... | |
| // Non-generic | |
| List list = new ArrayList(); | |
| Set set = new HashSet(); | |
| Map map = new HashMap(); | |
| public void mapExample () { | |
| // there must be a unique key | |
| map.put (21, "Mango"); // key-value | |
| map.put (22, "Mango"); | |
| map.put (22, "Orange"); | |
| map.put (23, "Orange"); | |
| uniqID.put (23, "Mango"); | |
| } | |
| public void listExample () { | |
| // duplicates are allowed | |
| list.add ("Mango"); | |
| list.add ("Mango"); | |
| list.add ("Orange"); | |
| list.add ("Orange"); | |
| list.add (23); | |
| list.add (23.87); | |
| } | |
| public void setExample () { | |
| // no duplicates | |
| set.add ("Mango"); | |
| set.add ("Mango"); | |
| set.add ("Orange"); | |
| set.add ("Orange"); | |
| set.add (23); | |
| set.add(34); | |
| } | |
| public void printList(Object obj) { | |
| System.out.println("Loop will run " + (list.size()) + " times"); | |
| if (obj instanceof List) { | |
| List list = (List) obj; // type casted to List | |
| for (int i = 0; i < list.size(); i++) { | |
| System.out.println(list.get(i)); | |
| } | |
| } | |
| if (obj instanceof Set) { | |
| Set set = (Set) obj; | |
| Iterator itr = set.iterator(); | |
| while (itr.hasNext()) { | |
| System.out.println (itr.next()); | |
| } | |
| } | |
| if (obj instanceof Map) { | |
| Map map = (Map) obj; | |
| Iterator itr = map.entrySet().iterator(); | |
| while (itr.hasNext()) { | |
| Map.Entry item = (Map.Entry) itr.next(); | |
| System.out.println(item.getKey() + ": " + item.getValue()); | |
| } | |
| } | |
| } | |
| public static void main (String [] args) { | |
| CollectionExample c = new CollectionExample(); | |
| c.listExample(); | |
| // c.setExample(); | |
| // c.mapExample(); | |
| c.printList(c.list); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment