Java - Collection - Completion

Programming question homework01

  1. Encapsulate a news class, including title and content attributes, provide get and set methods, override toString method, and print only title when printing object;

  2. Only one constructor with parameters is provided. When instantiating an object, only the title is initialized; And instantiate two objects;

    News 1: Morning News 56789101121314151617

    News 2: midday news 56789101121314151617

  3. Add the news object to the ArrayList collection and traverse in reverse order;

  4. In the process of traversing the collection, the news headlines are processed. If they exceed 15 words, only the first 15 are retained, and then "..." is added after them

  5. Print and traverse the processed news headlines on the console

package com.taotao.homework_.homework01;

import java.util.ArrayList;
import java.util.List;

/**
 * Create By Liu Hongtao
 * 2022/1/10 3:04
 */
public class HomeWork01 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new News("Morning news 56789101121314151617"));
        list.add(new News("Midday news 56789101121314151617"));

        //Reverse output
        for (int i = list.size() - 1; i >= 0; i--) {
            News news = (News)list.get(i);		//Downward transformation, use method
            System.out.println(Cut(news.getTitle()));

        }

        //In the process of traversing the collection, the news headlines are processed. If they exceed 15 words, only the first 15 are retained, and then "..." is added after them
    }
    public static String Cut(String str){
        if(str == null){
            return "";
        }
        if(str.length() > 15){
            str = str.substring(0,15) + "...";
        }
        return str;
    }
}
class News{ //Encapsulate news
    private String title;   //title
    private String body;    //content

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



    public String getTitle() {
        return title;
    }

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

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString(){
        return "The title of this news is:" + title;
    }
}

Programming problem homework02

  • Use ArrayList to complete various operations on the object Car {name,price}
  1. Add: add a single element
  2. remove: deletes the specified element
  3. contains: find whether the element exists
  4. size: get the number of elements
  5. isEmpty: judge whether it is empty
  6. Clear: clear
  7. addAll: add multiple elements
  8. containsAll: find whether multiple elements exist
  9. removeAll: deletes multiple elements
  • To use the enhanced for and iterator to traverse all cars, you need to override the toString method of the Car

Car car = new Car("BMW", 400000);

Car car2 = new Car("Bentley", 500000);

package com.taotao.homework_.homework02;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * Create By Liu Hongtao
 * 2022/1/10 3:42
 */
public class HomeWork02 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        Car car = new Car("bmw", 400000);

        list.add(new Car("bmw",400000));
        list.add(new Car("Bentley",500000));
        list.add(new Car("Benz",600000));

//        1. add: add a single element
        list.add(new Car("audi A8",800000));
        System.out.println(list);

//        2. remove: deletes the specified element
        list.remove(0); //Delete BMW

//        3. contains: check whether the element exists
        System.out.println(list.contains(car));

//        4. size: get the number of elements
        System.out.println(list.size());    //3

//        5. isEmpty: judge whether it is empty
        System.out.println(list.isEmpty()); //false

//        6. clear: clear
//        list.clear();

//        7. addAll: add multiple elements
        ArrayList arrayList = new ArrayList();
        arrayList.add(new Car("big truck",10));
        list.addAll(0,arrayList);
        System.out.println(list);

//        8. containsAll: check whether multiple elements exist
        System.out.println(list.containsAll(arrayList));        //true

//        9. removeAll: delete multiple elements
        list.removeAll(arrayList);
        System.out.println(list);

//        Using enhanced for traversal
        System.out.println("enhance for");
        for (Object o: list){
            System.out.println(o);
        }

//        Traversal using iterators
        System.out.println("Traversal using iterators");
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}
class Car{
    private String name;
    private int price;

    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 "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

Programming problem homework03

  • Complete the following tasks as required
  1. Instantiate a Map type object m with HashMap class. The key (String) and value (int) are used to store the employee's name and salary respectively. The stored data is as follows:

jack - 650; tom-1200 yuan; smith-2900 yuan;

  1. Change jack's salary to 2600 yuan;

  2. Raise the salary of all employees by 100 yuan;

  3. Traverse all employees in the set;

  4. Traverse all wages in the set;

package com.taotao.homework_.homework03;

import java.util.*;

/**
 * Create By Liu Hongtao
 * 2022/1/10 4:02
 */
public class HomeWork03 {
    public static void main(String[] args) {
        Map m = new HashMap();
        m.put("jack",650);
        m.put("tom",1200);
        m.put("smith",2900);

//        2. Change jack's salary to 2600 yuan;
        m.put("jack",2600);

//        3. Raise the salary of all employees by 100 yuan;
        Set keySet = m.keySet();    //key value
        for(Object key:keySet){
            //to update
            m.put(key,(Integer)(m.get(key)) + 100);
        }

//        4. Traverse all employees in the set;
        //Traverse EntrySet
        Set entrySet = m.entrySet();
        //iterator 
        System.out.println("Iterator traversal");
        Iterator iterator = entrySet.iterator();
        while(iterator.hasNext()){
            Map.Entry next = (Map.Entry)iterator.next();
            System.out.println(next.getKey());
        }
        

//        5. Traverse all wages in the set;
        //Enhanced for
        System.out.println("enhance for Traversal wage");
        Collection values = m.values();
        for (Object o: values){
            System.out.println(o);
        }
    }
}

Short answer homework04

  • This is to analyze how HashSet and TreeSet implement de duplication respectively
  1. The duplicate removal mechanism of HashSet: hashCode() + equals(), the bottom layer first obtains a hash value through the operation of the stored object, and obtains the corresponding index through the hash value. If there is no data found in the location of the table index, it will be stored directly. If there is data, it will be compared with equals. If it is different after comparison, it will be added, otherwise it will not be added.
  2. TreeSet's de duplication mechanism: if you pass in a Comparator anonymous object, use the implemented compare to de duplication. If the method returns 0, it is considered to be the same element / data and will not be added. If you do not pass in a Comparator anonymous object, use the compareTo of the Comparable interface implemented by the object you added to de duplication.

Code analysis question homework05

Whether the following code will throw an exception and explain the reason from the source code level. [source code reading + interface programming + dynamic binding]

package com.taotao.homework_.homework05;

import java.util.TreeSet;

/**
 * Create By Liu Hongtao
 * 2022/1/10 5:22
 */
public class HomeWork05 {
    public static void main(String[] args) {
        TreeSet treeSet = new TreeSet();
        //Analysis source code
        //add method, because the TreeSet() constructor does not pass in the anonymous inner class of the Comparator interface
        //So at the bottom, comparable <? super K> k = (Comparable <? super K>) key;
        //That is, convert Person to Comparable type
        treeSet.add(new Person());  //ClassCastException 

    }
}
class Person{
//    @Override
//    public int compareTo(Object o){
//        return 0;
//    }
}

Programming problem HomeWork06

This question is very interesting. If you don't pay attention, you will fall into a trap

  • Known: the Person class rewrites the hashCode and equals methods according to id and name. What does the following code output?
package com.taotao.homework_.homework06;


import java.util.HashSet;
import java.util.Objects;

/**
 * Create By Liu Hongtao
 * 2022/1/10 17:23
 */
public class HomeWork06 {
    public static void main(String[] args) {
        HashSet set = new HashSet();
        Person p1 = new Person(1001, "AA");
        Person p2 = new Person(1002, "BB");
        set.add(p1);
        set.add(p2);
        //Note that you cannot encapsulate here
        p1.name = "CC";
        set.remove(p1);     //p1 is no longer p1
        System.out.println(set);    //Two single chains
        set.add(new Person(1001,"CC"));
        System.out.println(set);    //2 same chains, 1 separate chain
        set.add(new Person(1001,"AA"));
        System.out.println(set);    //2 single chains, 2 same chains

    }
}
class Person{
  int id;
   String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return id == person.id && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }

//    @Override
//    public String toString() {
//        return "Person{" +
//                "id=" + id +
//                ", name='" + name + '\'' +
//                '}';
//    }
}


Try to write a comparison between Vector and ArrayList

Bottom structureeditionThread safety (synchronization) efficiencyExpansion multiple
ArrayListVariable arrayjdk1.2Unsafe and efficientIf there is a parameter constructor, expand the capacity by 1.5 times. If there is no parameter, 1, expand the capacity for the first time by 10; 2. Expand the capacity by 1.5 times from the second time
VectorVariable array Object []jdk1.0Safe and inefficientIf there is no parameter, the default value is 10, and the capacity will be expanded by 2 times when it is full; If there are parameters, the capacity shall be expanded by 2 times each time

After class conclusion

  • emm, the collection is still very important, and many details are still very ignorant;
  • Tree, red black tree
  • Expansion mechanism, expansion source code reading
  • Safety, efficiency
  • Selection of sets
  • Traversal of collection, iterator, enhanced for, for
  • LinkedList bidirectional linked list, LinkedHashSet bidirectional linked list
  • Implementation principle of HashMap and HashSet, array + linked list + red black tree
  • Map traversal mode, k - v, key value pair, anonymous inner class, iterator, enhanced for

Keywords: Java Back-end

Added by sagee on Mon, 10 Jan 2022 12:46:54 +0200