[Java Basics] Detailed Explanation of Collection Exercises

written in front


        Hello everyone, I am [ Lin-Xiaobai ], a student majoring in software engineering , who likes computer knowledge . I hope everyone can learn and progress together ! I am a college student , and my professional level is limited. If you find any mistakes or deficiencies , please correct me! thank you all! ! !

        If brothers and sisters are interested in my articles, please don't be stingy with your little hands, give more likes and follow ! ❤❤❤ Love you guys! ! !


Table of contents

written in front

The difference between Collection and Collections

The elements in Set cannot be repeated, so what method is used to distinguish whether it is repeated? Is it == or equals()? What is the difference between them?

Whether List, Set, Map inherit from Collection interface

Two objects have the same value (x.equals(y) == true), but they can have different hash codes. Is this sentence correct?

Tell the storage performance and characteristics of ArrayList, Vector, LinkedList

The difference between HashMap and Hashtable

The difference between ArrayList and Vector

What collection classes do you know? main method?

Define a variable of Collection interface type, refer to the implementation class of a Set collection, add a single element, add another collection, delete an element, judge whether the collection contains an element, judge whether it is empty, clear the collection, and return the element in the collection Number and other common operations.

Create an implementation class of the Set interface, add more than 10 elements, and traverse the collection elements through Iterator.

Create an implementation class of the Set interface, add more than 10 elements, and traverse the collection elements through foreach.

Create an implementation class of the Set interface, add more than 10 elements, and require sorting.

Create a Car class, including name, price attribute, constructor and other methods, create a test class, create an implementation class of the Set interface in the main method, add more than 5 Car objects, traverse the collection elements, and verify whether the repeated elements are filtered; if There is no filtering, and the filtering function is realized; the price of each car is reduced by 10,000 yuan, and then traversed to check whether the price has changed

Create an ArrayList instance object, add more than 10 elements, insert an element at position 2, obtain the element at position 5, delete the element at position 6, and modify the element at position 7;

Define a variable of the Map interface type, reference an implementation class, add a key-value pair, determine whether a certain key value is contained in the collection, obtain a value through a certain key value, delete a key-value pair through a certain key, and put another map Common operations such as adding the collection to the map collection, judging whether it is empty, clearing the collection, and returning the number of elements in the collection. Traversing the map collection in two ways

Use the implementation class of the Map interface to complete the simulation of employee salary (name--salary):

1) Add a few pieces of information

2) List all employee names

3) List all employee names and their salaries

4) Delete the employee information named "Tom"

5) Output Jack's salary, and add 1,000 yuan to his salary (realized by taking value)

6) Increase the wages of all employees whose wages are less than 1,000 yuan by 20% (realized by taking values)

Encapsulate a news class, including title, author, news content and release time, the news title is as follows:

Complete the following operations as required 

Complete the following operations as required

What is the result of running the following code?

epilogue


【Collection Intensive Talk】

This article will give you an in-depth understanding of [Java Basics] Java Collections (Part 2)

This article will give you an in-depth understanding of [Java Basics] Java collections (middle)

This article will give you an in-depth understanding of [Java Basics] Java Collections (Part 1)


The difference between Collection and Collections

Answer: Collection is the upper-level interface of the collection class, and the interfaces inherited from it mainly include Set and List.

Collections is a helper class for collection classes. It provides a series of static methods to implement operations such as searching, sorting, and thread safety on various collections.


The elements in Set cannot be repeated, so what method is used to distinguish whether it is repeated? Is it == or equals()? What is the difference between them?

Answer: The elements in the Set cannot be repeated. Use the equals() method to judge whether two Sets are equal

    The equals() and == methods determine whether the reference values ​​refer to the same object equals() is overridden in the class to return true when the contents and types of the two separate objects match


Whether List, Set, Map inherit from Collection interface

Answer: List, Set is, Map is not


Two objects have the same value (x.equals(y) == true), but they can have different hash codes. Is this sentence correct?

Answer: No, they have the same hash code


Tell the storage performance and characteristics of ArrayList, Vector, LinkedList

Answer: Both ArrayList and Vector use arrays to store data. The number of elements in this array is larger than the actual stored data for adding and inserting elements. They both allow direct indexing of elements by serial number, but inserting elements involves memory operations such as moving array elements, so Indexing data is fast but inserting data is slow. Because Vector uses the synchronized method (thread safety), its performance is usually worse than ArrayList, while LinkedList uses a doubly linked list for storage. Indexing data by serial number requires forward or backward traversal, but inserting data When you only need to record the front and rear items of this item, so the insertion speed is faster.


The difference between HashMap and Hashtable

answer:

1. Both HashMap and Hashtable implement the Map interface. Due to the non-thread safety of HashMap, it may be more efficient than Hashtable. The method of Hashtable is Synchronize, but HashMap is not. When multiple threads access Hashtable, there is no need to synchronize its methods, but HashMap must provide external synchronization for it.

2. HashMap allows null to be used as an entry key or value, but Hashtable does not.

3. HashMap removes the contains method of Hashtable and changes it to containsvalue and containsKey. Because the contains method is easily misleading.

4. Hashtable inherits from the Dictionary class, and HashMap is an implementation of the Map interface introduced by Java1.2.

5. The hash/rehash algorithms used by Hashtable and HashMap are roughly the same, so there will be no big difference in performance.


The difference between ArrayList and Vector

Answer: As far as ArrayList and Vector are concerned, there are mainly two aspects.

1. Synchronization: Vector is thread-safe, that is to say, it is synchronous, while ArrayList is not safe for line programs, not synchronous

2. Data growth: When growth is required, Vector defaults to the original 2, while ArrayList is 1.5 times the original


What collection classes do you know? main method?

Answer: The most commonly used collection classes are List and Map. The specific implementation of List includes ArrayList and Vector, which are variable-sized lists, which are more suitable for building, storing and manipulating element lists of any type of objects. List is suitable for accessing elements by numerical index.

Map provides a more general method of element storage. The Map collection class is used to store pairs of elements (called "keys" and "values"), where each key maps to a value.


Define a variable of Collection interface type, refer to the implementation class of a Set collection, add a single element, add another collection, delete an element, judge whether the collection contains an element, judge whether it is empty, clear the collection, and return the element in the collection Number and other common operations.

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Test {
    public static void main(String[] args) {
        //引用一个Set集合实现类
       Set set = new HashSet();
       //添加单个元素
       set.add("哈");
       set.add("士");
       set.add("奇");
       //添加另一个Set集合
       Set S = new HashSet();
       //将一个集合的所有元素添加到另一个集合
       S.addAll(set);
       //移除指定元素
       S.remove("哈");
       //判断集合中是否包含另一个元素
       System.out.println("集合中是否含有“哈”:" + S.contains("哈"));
       //判断是否为空
       System.out.println("集合是否为空:" + S.isEmpty());
       //清除集合
       S.clear();
       //返回集合元素个数
       System.out.println(S.size());
   }
}


Create an implementation class of the Set interface, add more than 10 elements, and traverse the collection elements through Iterator.

public static void main(String[] args) {
    //创建Set接口的实现类
    Set set1 = new HashSet();

    //添加10个以上的元素
    set1.add(22);
    set1.add(2);
    set1.add(55);
    set1.add(78);
    set1.add(5);
    set1.add(15);
    set1.add(7);
    set1.add(30);
    set1.add(9);
    set1.add(70);
    set1.add(11);

    //通过Iterator遍历此集合元素
    Iterator iterator = set1.iterator();
    while(iterator.hasNext()){
        System.out.print(iterator.next() + " ");
    }
}


Create an implementation class of the Set interface, add more than 10 elements, and traverse the collection elements through foreach.

public class SetTest {
    @Test
    public void test1() {
        HashSet<Object> objects = new HashSet<>();
        objects.add("123");
        objects.add("drtg");
        objects.add("25");
        objects.add("srthy");
        objects.add("zxc");
        objects.add("tdfh");
        objects.add("453");
        objects.add("SDGFrdsh");
        objects.add("zx254c");
        objects.add("sdGFSD");
        objects.add("578585");

        for (Object obj : objects) {
            System.out.println(obj);
        }
    }
}


Create an implementation class of the Set interface, add more than 10 elements, and require sorting.

@Test
    public void test2() {
        TreeSet<Object> set1 = new TreeSet<>();
        set1.add(123);
        set1.add(456);
        set1.add(789);
        set1.add("asd");
        set1.add("zxc");
        set1.add("sdfg");
        set1.add("qwe");
        set1.add(856);
        set1.add(649815);
        set1.add(4563);
        set1.add("dafdsgf");
        set1.add(65);
        set1.add(13);
        set1.add(63);

        for (Object obj : set1) {
            System.out.println(obj);
        }
    }


Create a Car class, including name, price attribute, constructor and other methods, create a test class, create an implementation class of the Set interface in the main method, add more than 5 Car objects, traverse the collection elements, and verify whether the repeated elements are filtered; if There is no filtering, and the filtering function is realized; the price of each car is reduced by 10,000 yuan, and then traversed to check whether the price has changed

car

public class Car {
    //创建Car类,包含name,price属性,构造器等方法

    private String name;

    private int price;

    public Car() {
    }

    public Car(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "name=" + name +
                "  price=" + price;
    }
}

Test class:

public class CarTest {
    public static void main(String[] args) {
        //创建测试类,在main方法中创建Set接口的实现类
        Set<Car> set = new TreeSet<>(new Comparator<Car>() {
            @Override
            public int compare(Car o1, Car o2) {
                int num = o1.getName().compareTo(o2.getName());
                int num1 = num == 0 ? o1.getPrice() - o2.getPrice() : num;
                return num1;
            }
        });

        //添加5个以上的Car对象
        set.add(new Car("沃尔沃",250000));
        set.add(new Car("大众",150000));
        set.add(new Car("凯迪拉克",350000));
        set.add(new Car("奥迪",550000));
        set.add(new Car("雷克萨斯",950000));
        set.add(new Car("雷克萨斯",950000));

        //遍历集合元素,验证重复元素是否过滤了,如果没有过滤,实现过滤功能
        for (Car car : set){
            System.out.println(car);
        }
        System.out.println("------------------------------");

        //把每个小车的price降10000元,再遍历,查看price是否已改变
        for (Car car : set){
            car.setPrice(car.getPrice()-10000);
            System.out.println(car);
        }
    }
}


Create an ArrayList instance object, add more than 10 elements, insert an element at position 2, obtain the element at position 5, delete the element at position 6, and modify the element at position 7;

@Test
    public void Test3() {
        ArrayList<Object> list = new ArrayList<>();
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(123);
        list.add(2, 365);
        System.out.println(list.get(5));
        list.remove(6);
        list.set(7, 666);
        Iterator<Object> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }


Define a variable of the Map interface type, reference an implementation class, add a key-value pair, determine whether a certain key value is contained in the collection, obtain a value through a certain key value, delete a key-value pair through a certain key, and put another map Common operations such as adding the collection to the map collection, judging whether it is empty, clearing the collection, and returning the number of elements in the collection. Traversing the map collection in two ways

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

    @Test
    public void test4() {
        // 定义一个Map接口类型的变量,引用一个实现类
        HashMap<String, String> hashMap = new HashMap<String, String>();

        //添加键值对
        hashMap.put("123", "你好");
        hashMap.put("蜂蜜", "柚子茶");
        hashMap.put("Lisa", "Rose");

        //判断集合中是否包含某一key值
        System.out.println(hashMap.containsKey("蜂蜜"));//ture

        //通过某一key值得到value值
        System.out.println(hashMap.get("123"));//你好

        //通过某一key删除键值对
        hashMap.remove("蜂蜜");
        System.out.println(hashMap); //{123=你好, Lisa=Rose}

        //把另一个map集合添加到此map集合
        HashMap<String, String> hashMap1 = new HashMap<String, String>();
        hashMap1.putAll(hashMap);

        //判断是否为空
        System.out.println(hashMap.isEmpty());//false

        //清除集合
        hashMap.clear();

        //返回集合里元素的个数
        System.out.println(hashMap.size()); //0

        //通过两种方法遍历上题中的map集合
        //方式一
        Set<String> keySet = hashMap1.keySet();
        for (String key : keySet) {
            String value = hashMap1.get(key);
            System.out.println("key:" + key + " , " + "value:" + value);
        }
        System.out.println("-------------------------");
        //方式二
        Set<Map.Entry<String, String>> entrySet = hashMap1.entrySet();
        for (Map.Entry<String, String> me : entrySet) {
            String key = me.getKey();
            String value = me.getValue();
            System.out.println("key:" + key + " , " + "value:" + value);
        }
    }


Use the implementation class of the Map interface to complete the simulation of employee salary (name--salary):

1) Add a few pieces of information

2) List all employee names

3) List all employee names and their salaries

4) Delete the employee information named "Tom"

5) Output Jack's salary, and add 1,000 yuan to his salary (realized by taking value)

6) Increase the wages of all employees whose wages are less than 1,000 yuan by 20% (realized by taking values)

@Test
    public void test5() {
        HashMap<String, Integer> hashMap = new HashMap<String, Integer>();

        //1)添加几条信息
        hashMap.put("Pamela", 5000);
        hashMap.put("Jack", 4800);
        hashMap.put("Tom", 6100);
        hashMap.put("Lee", 800);
        hashMap.put("Lara", 500);

        //2)列出所有的员工姓名
        Set<String> keySet = hashMap.keySet();
        System.out.println("员工姓名:" + keySet);

        //3)列出所有员工姓名及其工资
        for (String key : keySet) {
            //5)输出Jack的工资,并将其工资加1000元(通过取值实现)
            if (hashMap.get(key).equals("Jack")) {
                int value = hashMap.get(key) + 1000;
                hashMap.put("Jack", value);
            }

            //6)将所有工资低于1000元的员工的工资上涨20%(通过取值实现)
            if (hashMap.get(key) < 1000) {
                double value = (hashMap.get(key) + (hashMap.get(key) * 0.2));
                hashMap.put(key, (int) value);
            }
            int value = hashMap.get(key);
            System.out.println("姓名:" + key + " , " + "工资:" + value);
        }

        //4)删除名叫“Tom”的员工信息
        hashMap.remove("Tome");
    }


Encapsulate a news class, including title, author, news content and release time, the news title is as follows:

News 1: Many places in China are shrouded in smog, air quality becomes a hot topic again

News 2: The DPP held a "Fire Parade" in Taipei

News 3: The Spring Festival is approaching in Beijing, "house selling fever"

News 4: The Spring Festival is approaching in Beijing, "house selling fever"

Complete the following requirements (50 points in total, 10 points for each question):

1) To complete the design of the news class, it is required to assign a value to the news title by constructing a parameter when initializing the news class object, and it is required to instantiate four objects, and the content of the title is as the title.

2) When it is required to print the news object, directly print the news title;

3) When it is required to use the equals method to compare news, as long as the title is the same, it is considered to be the same news. Please output the comparison results of news 1 and news 2, and the comparison results of news 3 and news 4.

4) Store the news object in the HashSet collection, and traverse the collection to print the news object;

5) Print the number of news in the collection.

public class Journalism {
    //封装一个新闻类,包含标题、作者、新闻内容和发布时间,

    private String title;

    private String author;

    private String details;

    private Date date;

    public Journalism() {
    }

    public Journalism(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "标题:" + title +
                "\n作者:" + author +
                "\n内容:" + details +
                "\n发布时间:" + date ;
    }

    //要求使用equals方法比较新闻时,只要标题相同,就认为是同一新闻

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Journalism that = (Journalism) o;

        return title != null ? title.equals(that.title) : that.title == null;
    }

    @Override
    public int hashCode() {
        return title != null ? title.hashCode() : 0;
    }
}
public class Test {
    public static void main(String[] args) {
        //创建HashSet集合对象
        Set<Journalism> set = new HashSet<Journalism>();

        //要求在初始化新闻类对象时 ,通过构造传参的形式对新闻标题赋值,并要求实例化四个对象,标题内容如题。
        Journalism journalism1 = new Journalism("中国多地遭雾霾笼罩空气质量再成热议话题");
        Journalism journalism2 = new Journalism("民进党台北举行“火大游行“");
        Journalism journalism3 = new Journalism("春节临近北京“卖房热”");
        Journalism journalism4 = new Journalism("春节临近北京“卖房热”");

        //将新闻对象存入HashSet集合中
        set.add(journalism1);
        set.add(journalism2);
        set.add(journalism3);
        set.add(journalism4);

        //要求打印新闻对象时,直接打印新闻标题;
        for (Journalism journalism : set){
            System.out.println(journalism);
            System.out.println("------------------------");
        }

        //只要标题相同,就认为是同一新闻,请输出新闻一与新闻二的比较结果,新闻三与新闻四的比较结果
        System.out.println("新闻一与新闻二的比较结果:"+journalism1.equals(journalism2));
        System.out.println("新闻三与新闻四的比较结果:"+journalism3.equals(journalism4));

        //打印集合中新闻数量
        System.out.println("集合中新闻数量:"+set.size());
    }
}


Complete the following operations as required 

  1. Generate 10 random numbers with values ​​between 100 and 200;
  2. Store these ten numbers in the HashSet collection (it is possible that the length of the collection is less than 10).
  3. Convert this HashSet collection into an ArrayList collection
  4. Re-sort the ArrayList collection in ascending order;
  5. Use foreach to traverse the collection;
 @Test
    public void test4() {
        HashSet<Integer> hashset = new HashSet<Integer>();
        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            int j = random.nextInt(100) + 101;
            hashset.add(j);
        }
        System.out.println(hashset);

        ArrayList<Integer> list = new ArrayList<Integer>(hashset);
        list.sort(Comparator.naturalOrder());
        list.forEach(integer -> {
            System.out.print(integer + " ");
        });
    }


Complete the following operations as required

1) Encapsulate a car class, including String name, int speed attributes, instantiate three objects in the test class: c1, c2, c3, respectively set the name as: "Alto", "BMW", "Mercedes", and the speed respectively Set to: 100, 200, 300

2) Use the Map collection object m1 to save these three car objects as keys, and then store the int car price as a value in the value of m1. The corresponding prices of the above three cars are 10000, 500000, 2000000

3) Traverse the keys of m1 and print the name attribute

4) Calculate the price of "BMW" in m1 through a suitable method, and print the result;

5) After depreciation, all cars are reduced to 80% of the original price, please print the price of "BMW" after the price reduction

   @Test
    public void test6() {
        //在测试类中实例化三个对象:c1,c2,c3,
        //分别设置name为:“奥拓”,“宝马”,“奔驰”,速度分别设置为:100,200,300
        Car c1 = new Car("奥拓", 100);
        Car c2 = new Car("宝马", 200);
        Car c3 = new Car("奔驰", 300);

        //2 )使用Map集合对象m1将这三个汽车类对象保存成key
        HashMap<Car, Integer> hashMap = new HashMap<>();

        //然后将int型的汽车价钱作为值保存在m1的value中,上述三款汽车分别对应的价钱是10000,500000,2000000
        hashMap.put(c1, 10000);
        hashMap.put(c2, 500000);
        hashMap.put(c3, 2000000);

        //3 )遍历m1的键,打印name属性
        Set<Car> keySet = hashMap.keySet();
        int i = 1;
        for (Car car : keySet) {
            System.out.print("car" + i++ + "name:" + car.getName() + "   ");
        }

        for (Car car : keySet) {
            //4 )通过合适的方法,求出m1中“宝马”的价格,并打印结果;
            if (car.getName().equals("宝马")) {
                int price = hashMap.get(car);
                System.out.println("\n宝马价格为:" + price);
            }
            //5 )经过折旧,所有汽车都降价到原来的80%,请打印降价后“宝马”的价格
            double price1 = hashMap.get(car) - (hashMap.get(car) * 0.2);
            hashMap.put(car, (int) price1);
        }
        //请打印降价后“宝马”的价格
        for (Car car : keySet) {
            if (car.getName().equals("宝马")) {
                int price = hashMap.get(car);
                System.out.println("宝马价格为:" + price);
            }
        }
    }


What is the result of running the following code?

public static void main(String[] args) {
    Integer[] datas = {1,2,3,4,5};
    List<Integer> list = Arrays.asList(datas);
    list.add(5);
    System.out.println(list.size());
}

Run exception, not allowed to add element


epilogue


I will continue to update the article! I hope everyone will click three times , your encouragement is the motivation for the author to keep updating

Guess you like

Origin blog.csdn.net/qq_34025246/article/details/128160105