优秀的编程知识分享平台

网站首页 > 技术文章 正文

Java|没有指针移动(算术运算),集合类如何实现基于引用的循环

nanyue 2024-08-17 19:17:45 技术文章 19 ℃

Java一切皆对象,利用方法改变和访问对象状态便可以控制容器内元素(对象)的遍历或循环。需要注意的是,Java虽然在编译器提供的语法层面没有提供指针及其算术操作,但在JVM层面却是有指针操作的。

0 栈容器.isEmpty()

public class WildCardNeedDemo {
    public static void main(String[] args ) {
        GenericStack<Integer> intStack = new GenericStack<>();
        intStack.push(1); // 1 is autoboxed into an Integer object
        intStack.push(2);
        intStack.push(?2);
        
        System.out.print("The max number is " + max(intStack));
    }
    
    /** Find the maximum in a stack of numbers */
    public static double max(GenericStack<Number> stack) {
        double max = stack.pop().doubleValue(); // Initialize max
        
        while(!stack.isEmpty()) {
            double value = stack.pop().doubleValue();
            if(value > max)
                max = value;
        }

1 for each

import java.util.*;

public class TestForEach {
    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>();
        collection.add("New York");
        collection.add("Atlanta");
        collection.add("Dallas");
        collection.add("Madison");
        
        collection.forEach(e ?> System.out.print(e.toUpperCase() + " "));
    }
}
// ……
treeMap.forEach( (name, age) ?> System.out.print(name + ": " + age + " "));
// ……

2 迭代器iterator.hasNext()

每个集合都是可迭代的,可以获取其迭代器对象以遍历集合中的所有元素(Each collection is Iterable. You can obtain its Iterator object to traverse all the elements in the collection)。

import java.util.*;

public class TestIterator {
    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>();
        collection.add("New York");
        collection.add("Atlanta");
        collection.add("Dallas");
        collection.add("Madison");
        
        Iterator<String> iterator = collection.iterator();
        while(iterator.hasNext()) {
            System.out.print(iterator.next().toUpperCase() + " ");
        }
        System.out.println();
    }
}

方法实现Demo:

public boolean hasNext() {
    if(current < list.size())
        return true;
    return false;
}

@Override /** Get the current element and move to the next */
public E next() {
    return list.get(current++); // int current = 0; Point to the current element in list
}

3 利用for范围迭代(底层也是迭代器实现)

public class SortStringIgnoreCase {
    public static void main(String[] args) {
        java.util.List<String> cities = java.util.Arrays.asList
        ("Atlanta", "Savannah", "New York", "Dallas");
        cities.sort((s1, s2) ?> s1.compareToIgnoreCase(s2));
        
        for(String s: cities) {
            System.out.print(s + " ");
        }
    }
}

The AbstractSet class extends AbstractCollection and partially implements Set. The AbstractSet class provides concrete implementations for the equals method and the hashCode method. The hash code of a set is the sum of the hash codes of all the elements in the set. Since the size method and iterator method are not implemented in the AbstractSet class, AbstractSet is an abstract class.

AbstractSet类扩展了AbstractCollection并部分实现了Set。AbstractSet类为equals方法和hashCode方法提供了具体的实现。集合的哈希代码是集合中所有元素的哈希代码之和。因为size方法和迭代器方法没有在AbstractSet类中实现,所以AbstractSet是一个抽象类。

import java.util.*;

public class TestHashSet {
    public static void main(String[] args) {
        // Create a hash set
        Set<String> set = new HashSet<>();
        
        // Add strings to the set
        set.add("London");
        set.add("Paris");
        set.add("New York");
        set.add("San Francisco");
        set.add("Beijing");
        set.add("New York");
        
        System.out.println(set);
        
        // Display the elements in the hash set
        for(String s: set) {
            System.out.print(s.toUpperCase() + " ");
        }
        
        // Process the elements using a forEach method
        System.out.println();
        set.forEach(e ?> System.out.print(e.toLowerCase() + " "));
    }
}

4 利用容器方法size()

public class TestQueue {
    public static void main(String[] args) {
        java.util.Queue<String> queue = new java.util.LinkedList<>();
        queue.offer("Oklahoma");
        queue.offer("Indiana");
        queue.offer("Georgia");
        queue.offer("Texas");
        
        while(queue.size() > 0)
            System.out.print(queue.remove() + " ");
    }
}

5 数组length

import java.util.*;

public class CountOccurrenceOfWords {
    public static void main(String[] args) {
        // Set text in a string
        String text = "Good morning. Have a good class. " +
        "Have a good visit. Have fun!";
        
        // Create a TreeMap to hold words as key and count as value
        Map<String, Integer> map = new TreeMap<>();
        
        String[] words = text.split("[\\s+\\p{P}]");
        for(int i = 0; i < words.length; i++) {
            String key = words[i].toLowerCase();
            
            if(key.length() > 0) {
                if(!map.containsKey(key)) {
                    map.put(key, 1);
                }
                else {
                    int value = map.get(key);
                    value++;
                    map.put(key, value);
                }
            }
        }
        
        // Display key and value for each entry
        map.forEach((k, v) ?> System.out.println(k + "\t" + v));
    }
}

6 链式存储实现顺序表(与C++的实现没有区别)

Node<E> current = head;
while(current != null) {
    System.out.println(current.element);
    current = current.next;
}

7 链式存储实现二叉搜索树的搜索操作:

public boolean search(E e) {
    TreeNode<E> current = root; // Start from the root
    
    while(current != null)
        if(e < current.element) {
        current = current.left; // Go left
    }
    else if(e > current.element) {
        current = current.right; // Go right
    }
    else // Element e matches current.element
        return true; // Element e is found
    
    return false; // Element e is not in the tree
}

--End

最近发表
标签列表