Master Java Basics: Essential Object, String, and Collection Methods Explained
This guide walks Java beginners through the fundamental classes Object, String, and Collection, detailing their most frequently used methods, key differences such as == versus equals, and practical code examples for overriding methods, string concatenation optimization, and common collection operations.
Object Class: Core Methods
All Java classes inherit Object. It provides fundamental methods.
Commonly Used Methods
toString()– returns string representation (class name + memory address by default). equals(Object obj) – checks equality, default compares memory addresses. hashCode() – returns hash code for hash‑based collections. getClass() – returns runtime class of the object.
Difference between == and equals
==compares primitive values or reference addresses for objects. equals defaults to == but many classes (e.g., String) override it to compare content.
Code Example
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Override toString
@Override
public String toString() {
return "姓名:" + name + ",年龄:" + age;
}
// Override equals
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
// Override hashCode
@Override
public int hashCode() {
return name.hashCode() + age;
}
public static void main(String[] args) {
Person p1 = new Person("张三", 20);
Person p2 = new Person("张三", 20);
System.out.println(p1); // 姓名:张三,年龄:20
System.out.println(p1 == p2); // false
System.out.println(p1.equals(p2)); // true
}
}Key point: When customizing equality, both equals and hashCode must be overridden.
String Class: Immutable Text
Stringobjects are immutable; each modification creates a new instance.
Frequently Used Methods
length()– returns number of characters. charAt(int index) – returns character at given index. substring(start, end) – extracts a substring (start inclusive, end exclusive). equals() – case‑sensitive content comparison. equalsIgnoreCase() – case‑insensitive comparison. contains() – checks if a sequence is present. indexOf() – returns first index of a character or substring. trim() – removes leading and trailing whitespace. replace() – replaces occurrences of a substring. split() – splits the string based on a regex.
String Concatenation Optimization
Repeated concatenation inside loops creates many temporary objects and hurts performance. StringBuilder – efficient for single‑threaded concatenation. StringBuffer – thread‑safe alternative.
Code Demonstration
public class StringTest {
public static void main(String[] args) {
String str = "Hello Java";
System.out.println(str.length()); // 10
System.out.println(str.charAt(0)); // H
System.out.println(str.substring(0,5)); // Hello
System.out.println(str.contains("Java")); // true
System.out.println(str.trim()); // Hello Java
// Efficient concatenation
StringBuilder sb = new StringBuilder();
sb.append("2026");
sb.append(" 入门 Java");
System.out.println(sb.toString()); // 2026 入门 Java
}
}Key point: Use StringBuilder (or StringBuffer in multithreaded contexts) for loop concatenation; distinguish == from equals .
Collection Framework: Single‑Element Containers
Collectionis the top‑level interface for single‑element containers.
Common Implementations
ArrayList– ordered, allows duplicates, backed by an array, fast random access. HashSet – unordered, no duplicates, automatically removes repeats.
Universal Methods
add(E e)– adds an element. remove(Object o) – removes a specific element. contains(Object o) – checks presence. size() – returns number of elements. isEmpty() – checks if collection is empty. clear() – removes all elements.
ArrayList Example
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("MySQL");
list.add("Vue");
System.out.println("集合长度:" + list.size()); // 3
System.out.println("是否包含 Java:" + list.contains("Java")); // true
for (String s : list) {
System.out.println(s);
}
list.remove("MySQL");
list.clear();
}
}HashSet Example
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(10); // duplicate ignored
System.out.println(set); // [20, 10] (order not guaranteed)
}
}Key point: ArrayList preserves order and allows duplicates; HashSet removes duplicates automatically; avoid removing elements during iteration to prevent ConcurrentModificationException.
Common Pitfalls for Beginners
When defining custom equality, always override both equals and hashCode.
Distinguish == (reference comparison) from equals (content comparison) for String.
Use StringBuilder for loop concatenation; prefer ArrayList for ordered collections and HashSet for deduplication.
Learning Summary
Object → Master object comparison and printing overrides, foundation of OOP.
String → Most used type; proficient with substring, search, replace APIs.
Collection → Bulk data storage; skilled in add/remove/contains/iteration.Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
