Java编程思想 持有对象和容器类

持有对象

一. Arrays

1.基本概念

特点:大小固定

含义:数组也可以看成是对象,数组中的每个元素相当于该对象的成员变量

举例:如何返回数组引用

public class Test {
    private static Random rand = new Random(47);//Random用法
    static final String[] FLAVORS = {
            "A","B","C","D","E","F","G"
    };
    public static String[] flavorset(int n) {       
        String[] results = new String[n];//JAVA中数组初始化范围可以为变量
        boolean picked[] = new boolean[FLAVORS.length];
        for(int i = 0; i < n; i++) {
            int t;
            do
                t = rand.nextInt(FLAVORS.length);//nextInt,Random的使用方法
            while(picked[t]);//do while用法,记得加分号
            results[i] = FLAVORS[t];
            picked[t] = true;//false
        }
        return results;     
    }
    public static void main(String[] args){     
       for(int i = 0; i < 7; i++) {
           System.out.println(Arrays.toString(flavorset(3)));//数组的输出方法
       }    
    }
}
2.数组中的比较:

数组之间的比较:

Arrays.equals(a1,a2),数组元素个数必须相等,并且对应位置的元素也相等。

数组元素之间的比较:

使用Comparable接口

import java.util.Arrays;
public class ComType implements Comparable<ComType>{//继承Comparable接口
    int i;
    int j;
    private static int count = 1;
    public ComType(int n1, int n2) {//写构造器,接收外部参数
        i = n1;
        j = n2;
    }
    public String toString() {//如果有必要,重写toString方法
        String result = "[i = " + i + ", j = " + j + "]";
        if(count++ % 3 == 0) 
            result += "\n";
        return result;
    }
    public int compareTo(ComType rv) {//重写compareTo方法
        if(i < rv.i) return -1;
        if(i > rv.i) return 1;
        if(j < rv.j) return -1;
        if(j > rv.j) return 1;
        return 0;
    }   
    public static void main(String[] argv) {//最后测试输出
        ComType[] a = new ComType[6];//注意开6的数组,下面是0到5
        a[0] = new ComType(2,3);a[1] = new ComType(2,5);a[2] = new ComType(4,7);
        a[3] = new ComType(6,9);a[4] = new ComType(3,7);a[5] = new ComType(3,4);
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
    }
}

使用Comparator接口:

两者不同之处:

Comparable接口将比较代码嵌入到需要进行比较的类的自身代码中,而Comparator接口在一个独立的类中实现比较。

import java.util.*;
class ComTypeComparator implements Comparator<ComType>{ //<>里面应该为要比较的元素类型
    public int compare(ComType a, ComType b) {//方法必须是public的
        if(a.i < b.i) return -1;
        if(a.i > b.i) return 1;
        if(a.j < b.j) return -1;
        if(a.j > b.j) return 1;
        return 0;
    }   
}
public class ComType {  
    int i;
    int j;
    static int count = 1;
    public ComType(int i, int j) {
        this.i = i;
        this.j = j;
    }   
    public String toString() {
        String result = "[i = " + i + ", j = " + j + "]";
        if(count++ % 3 == 0) 
            result += "\n";
        return result;
    }   
    public static void main(String[] argv) {
        ComType[] a = new ComType[6];
        a[0] = new ComType(2,3);a[1] = new ComType(2,5);a[2] = new ComType(4,7);
        a[3] = new ComType(6,9);a[4] = new ComType(3,7);a[5] = new ComType(3,4);
        Arrays.sort(a, new ComTypeComparator());
        System.out.println(Arrays.toString(a));
    }   
}
3.数组的复制和查找:

Arrays.binarySearch使用之前必须将元素排好序。如果数组中有重复的元素,不确定返回的是哪一个元素的位置。

如果使用Comparator排序了数组,那么在使用binarySearch时必须提供同样的Comparator

基本类型数组和对象数组都可以复制,如果只复制对象数组,只是复制了对象的引用,而不是对象本身的拷贝。这被称为“浅复制”。

import java.util.Arrays;
public class ComType{   
    public static void main(String[] argv) {
        Integer[] a = new Integer[5];
        Arrays.fill(a, 3);
        a[2] = 9;
        Integer[] b = new Integer[10];
        Arrays.fill(b, 23);
        System.arraycopy(a, 0, b, 0, a.length); 
        b[0] = 1;
        Arrays.sort(b);
        System.out.println(Arrays.toString(b));
        System.out.println(Arrays.binarySearch(b,9));
    }
}

二. 容器类

1.数组与容器的区别:

数组只能保存特定类型。

容器类只能保存对象的引用。而数组可以创建为直接保存基本类型,也可以保存对象的引用。2.

2.容器类简介:

Collection:一个独立元素的序列,这些元素都服从一条或多条规则。List必须按照插入的顺序保存元素,而Set不能有重复元素。Queue按照排队规则来确定对象产生的顺序。

如果在列表中频繁插入和删除LinkedList更合适,否则ArrayList效率更高。HashSet提供最快的查询速度,TreeSet使元素处于排序状态。

Map:一组成对的“键值对”对象,允许用键来查找值。TreeMap按照比较结果的升序保存键。LinkedHashMap按照插入顺序保存键。

import java.util.*;
public class Test{
    static Collection<String> fill(Collection<String> c){
        c.add("dog");
        c.add("cat");
        c.add("dog");
        return c;
    }
    static Map<String, String> fill(Map<String, String> c){
        c.put("dog", "Bosco");
        c.put("dog", "Spot");
        c.put("cat", "Rags");
        return c;
    }
    public static void main(String[] argv) {
        System.out.println(fill(new LinkedList<String>()));
        System.out.println(fill(new ArrayList<String>()));
        System.out.println(fill(new HashSet<String>()));
        System.out.println(fill(new TreeSet<String>()));
        System.out.println(fill(new HashMap<String, String>()));
        System.out.println(fill(new TreeMap<String, String>()));
        System.out.println(fill(new LinkedHashMap<String, String>()));
    }
}
输出结果为:
[dog, cat, dog]
[dog, cat, dog]
[cat, dog]//Set去掉了重复元素
[cat, dog]
{cat=Rags, dog=Spot}//注意键值对的写法
{cat=Rags, dog=Spot}
{dog=Spot, cat=Rags}
3.添加一组元素的方法:

Arrays.asList()接受一个数组或是一个用逗号分隔的元素列表。转换后的List对象是一个size不能改变的对象。如果对该对象做增加删除操作,将会报不支持的异常。

Collection<Integer> a = new ArrayList<Integer>(Array.asList(1, 2, 3, 4));

a.addAll()成员方法只能接受另一个Collection对象作为参数。

Collections.addAll()方法可以支持可变参数列表。例如:

Collections.addAll(collection, 11, 12, 14);

4.List用法:
import java.util.*;
public class Test{
    public static void main(String[] argv) {
        List<Integer> a = new ArrayList<Integer>();
        Collections.addAll(a, 1, 2, 3, 67, 34, 19);
        System.out.println(a);
        a.remove(3);//删去值为3的元素
        System.out.println(a);
        System.out.println(a.indexOf(1));//查找元素所在的索引
        System.out.println(a.subList(1, 3));//获得下标为1和2的两个元素
        System.out.println(a.containsAll(a.subList(1,3)));
        System.out.println(a.get(2));//通过索引查找元素
        a.removeAll(a.subList(2, 3));//删去第2个元素
        System.out.println(a.isEmpty());
        a.clear();
        System.out.println(a.isEmpty());
    }
}

LinkedListremoveLast()方法移除并返回列表中的最后一个元素。addFirst()方法将元素插到列表端部,addLast()方法将元素插到列表尾部。

5.迭代器

迭代器是一个对象,它的工作是遍历并选择序列中的对象,而不必关心序列底层的结构。

迭代器只能单向移动。

import java.util.*;
public class Test{
    public static void main(String[] argv) {
        List<Integer> a = new ArrayList<Integer>();
        Collections.addAll(a, 1, 2, 3, 67, 34, 19);
        Iterator<Integer> it = a.iterator();//记住迭代器的写法
        while(it.hasNext()) {//it.hasNext()
            System.out.println(it.next());//it.next()
            it.remove();//it.remove()
             //如果要达到每个元素都删除的效果,必须先调用it.next(),再调用it.remove()
        }
        System.out.println(a);
    }
}

迭代器更多用于方法的参数中:

public static void display(Iterator<Pet> it)

这样对于Pet类型构成的任何容器类,都可以实现遍历。

6.Foreach语句:

Foreach简化了迭代器。

for( 元素类型 变量名 :Collection集合 & 数组 )

for(Integer b: a) {
    System.out.println(b);
}

猜你喜欢

转载自blog.csdn.net/ljfyyj/article/details/80976936