data structure

Data structure type

Array memory usage is small, but it is not good at adding elements because it is necessary to determine the length at the time of declaration. List Data structure that can be duplicated and can handle elements in order Set Non-duplicate, unordered data structure Map Duplicate will be replaced with the newest element

ArrayList Feature You don't have to worry about the length of the array, and you can easily add elements. The order of the elements is the order in which they were added.

Method Add element Get element fetch

Example

array.add("France");
String country = array.get(2);
System.out.println(country);

output


France

Sorting elements

Collections.sort(Name of ArrayList);

HashMap Feature A data structure that associates an element with a key and retrieves the element with the key. Also, do not allow duplication. The order of the elements is not the order in which they were inserted.

Method Add put element Get element fetch Gets the getOrDefault element and returns the specified default value if it does not exist keySet Returns all keys

Example

HashMap<String,String> map = new HashMap<String,String>();
map.put("Apple", apple");
map.put("Grape", "grapes");

System.out.println(map.get("Apple"));
System.out.println(map.getOrDefault("Bread","Raisins"));

System.out.println();

for(String key:map.keySet()){
System.out.println(map.get(key));
}

output


apple
Raisins

apple
grapes

Sorting elements

Map<String, String> sortedMap = new TreeMap<>(The name of the HashMap);

TreeSet Feature You don't have to worry about the length of the array, and you can easily add elements. In addition, it does not allow duplication and is automatically sorted. Be careful when extracting elements.

Method Add element remove element remove Returns true if the isEmpty element is empty

Example

TreeSet<String> ts = new TreeSet<String>();
ts.add("C");
for (String a : ts) {
   System.out.println(a);
}

output


C

Citation, reference https://www.javadrive.jp/start/ https://eng-entrance.com/java-array-list

Recommended Posts

data structure
List data structure [Java / Scala]
[Java] Basic structure
[Swift] Type type ~ Structure ~