Veröffentlicht · wird verbessert
Java-Anleitung · 3/6
Dieses Kapitel ist vorerst nur auf Englisch verfügbar.
Every Java value is either a primitive or a reference to an object. This chapter covers that split, arrays, your own types (classes, interfaces, records, enums), generics, and the everyday collections List, Map, and Set.
Primitives hold their value directly and can never be null. Everything else is an object, and a variable of an object type holds a reference to it.
| Primitive | Size | Wrapper class |
|---|---|---|
byte, short, int, long | 8, 16, 32, 64-bit integers | Byte, Short, Integer, Long |
float, double | 32, 64-bit floating point | Float, Double |
char | one 16-bit UTF-16 code unit | Character |
boolean | true or false | Boolean |
Collections store only objects, so an int is wrapped in an Integer automatically (autoboxing). Watch for two pitfalls: == on wrappers compares references, so use equals, and unboxing a null throws NullPointerException.
int a = 1_000; // underscores for readability
long big = 9_000_000_000L; // long literals need an L
double pi = 3.14159;
Integer x = 1000; // autoboxing
Integer y = 1000;
System.out.println(x.equals(y)); // true
System.out.println(x == y); // reference comparison, may be false
int parsed = Integer.parseInt("42");
String text = String.valueOf(parsed);An array is a fixed-length sequence of one type. Its size is in the length field, indexes start at zero, and going out of bounds throws ArrayIndexOutOfBoundsException. java.util.Arrays has helpers for sorting and printing.
int[] scores = {90, 75, 88};
String[] names = new String[3]; // every slot starts as null
names[0] = "Duke";
java.util.Arrays.sort(scores);
System.out.println(java.util.Arrays.toString(scores)); // [75, 88, 90]
int[][] grid = new int[2][3]; // 2 rows, 3 columns
grid[1][2] = 7;For data that grows or shrinks, use a collection such as ArrayList.
An interface is a contract of methods to implement, optionally with shared methods. A class can implement many interfaces but extend only one class.
defaultRecords declare immutable data carriers concisely; the compiler generates the constructor, accessors, equals, hashCode, and toString. Accessors are named after the components: radius(), not getRadius().
interface Shape {
double area();
default String describe() {
return getClass().getSimpleName() + " area=" + area();
}
}
record Circle(double radius) implements Shape {
Circle { // compact constructor for validation
if (radius < 0) throw new IllegalArgumentException("radius < 0");
}
public double area() { return Math.PI * radius * radius; }
}
record Rect(double width, double height) implements Shape {
public double area() { return width * height; }
}
enum Status {
ACTIVE("active"), SUSPENDED("suspended");
private final String label;
Status(String label) { this.label = label; }
String label() { return label; }
}An enum turns a fixed set of constants into a real type. It can carry fields and methods, works naturally with switch, and provides valueOf and values() for free.
Generics parameterize code by type, so one implementation serves many types while the compiler checks everything up front instead of leaving casts for runtime. Type arguments must be reference types, which is why you write List<Integer> rather than List<int>.
record Pair<A, B>(A first, B second) {}
static <T extends Comparable<T>> T max(java.util.List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
var pair = new Pair<>("age", 30); // diamond operator infers the types
String key = pair.first();
int biggest = max(java.util.List.of(3, 9, 4)); // 9A bound such as T extends Comparable<T> lets you call that type's methods inside the generic code. For parameters you only read from, wildcards like List<? extends Number> make an API accept more argument types.
The collections framework in java.util separates interfaces from implementations. The convention is to declare variables with the interface type and pick the implementation that suits the job.
| Interface | Common implementations | Behavior |
|---|---|---|
List | ArrayList, LinkedList | Ordered, duplicates allowed |
Set | HashSet, LinkedHashSet, TreeSet | No duplicates |
Map | HashMap, LinkedHashMap, TreeMap | Key-value pairs |
import java.util.*;
List<String> langs = new ArrayList<>(List.of("Java", "Go"));
langs.add("Rust");
langs.remove("Go");
Set<String> tags = new HashSet<>();
tags.add("jvm");
tags.add("jvm"); // duplicate is ignored
System.out.println(tags.size()); // 1
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 3);
stock.merge("apple", 2, Integer::sum); // 5
int pears = stock.getOrDefault("pear", 0);
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + "=" + e.getValue());
}
List<Integer> fixed = List.of(1, 2, 3); // unmodifiableCollections from List.of, Set.of, and Map.of are unmodifiable, and add throws UnsupportedOperationException; copy them into a mutable collection, as in the first line, when you need changes. HashMap and HashSet promise no order: use LinkedHashMap for insertion order or TreeMap for sorted keys.
equals.List, Set, and Map cover most everyday data structures.
0 Kommentare
Anmelden · Melde dich an, um einen Kommentar zu schreiben.
Schreib den ersten Kommentar.