Created
October 17, 2019 15:28
-
-
Save chenhong805/2383170ae1f95eac2b6efebb8de37dd9 to your computer and use it in GitHub Desktop.
basic data structures usage examples in java
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.*; | |
public class HelloWorld{ | |
public static void main(String []args){ | |
// Arrays 0 | |
System.out.println("=============="); | |
int[] a0 = new int[100]; | |
for(int i = 100; i > 0; i--) { | |
a0[100 - i] = 101 * (i << 1); | |
} | |
Arrays.sort(a0); | |
for(int i = 0; i < a0.length; i++) { | |
System.out.println(a0[i]); | |
} | |
// PQ 1 | |
System.out.println("=============="); | |
PriorityQueue<String> q = new PriorityQueue(10, new Comparator<String>() { | |
public int compare(String s1, String s2) { | |
return s2.compareTo(s1); | |
} | |
}); | |
q.add("123"); | |
q.add("321"); | |
Iterator<String> iter = q.iterator(); | |
while(iter.hasNext()) { | |
System.out.println(iter.next()); | |
} | |
for(String s: q) { | |
System.out.println(s); | |
} | |
// Map/HashMap 2 | |
System.out.println("=============="); | |
Map<String, Integer> m2 = new HashMap<>(); | |
m2.put("123", 123); | |
m2.put("124", 124); | |
Iterator<Map.Entry<String,Integer>> i2 = m2.entrySet().iterator(); | |
while(i2.hasNext()) { | |
Map.Entry<String, Integer> e2 = i2.next(); | |
System.out.println(e2.getKey()); | |
System.out.println(e2.getValue()); | |
} | |
// Bits 3 | |
System.out.println("=============="); | |
int i3 = 100; | |
System.out.println(i3 >> 2); | |
System.out.println(i3 >>> 2); | |
int ii3 = -100; | |
System.out.println(ii3 >> 2); | |
System.out.println(ii3 >>> 2); | |
// Math 4 | |
System.out.println("=============="); | |
System.out.println(java.lang.Math.pow(2, 4)); | |
System.out.println(java.lang.Math.log(2)); | |
System.out.println(java.lang.Math.abs(-2)); | |
// TreeSet 5 | |
System.out.println("=============="); | |
TreeSet<String> tm5 = new TreeSet(new Comparator<String>(){ | |
public int compare(String s1, String s2) { | |
return s2.compareTo(s1); | |
}; | |
}); | |
tm5.add("123"); | |
tm5.add("124"); | |
tm5.add("125"); | |
tm5.add("135"); | |
for(String a: tm5) { | |
System.out.println(a); | |
} | |
System.out.println(tm5.ceiling("126")); // 125, ceilingKey, headMap | |
System.out.println(tm5.floor("126")); // 135, floorKey, tailMap | |
// reverse: descendingMap | |
// LinkedList 6 | |
System.out.println("=============="); | |
LinkedList<String> ll = new LinkedList<>(); | |
ll.addFirst("123"); | |
ll.addLast("321"); | |
for(String a: ll) { | |
System.out.println(a); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment