Java

您所在的位置:网站首页 java数组集合面试题 Java

Java

2023-08-20 14:03| 来源: 网络整理| 查看: 265

1、HashMap排序题

已知一个 HashMap集合, User 有 name(String)和 age(int)属性。请写一个方法实现对HashMap 的排序功能,该方法接收 HashMap为形参,返回类型为 HashMap,要求对 HashMap 中的 User 的 age 倒序进行排序。排序时 key=value 键值对不得拆散。 

注意:要做出这道题必须对集合的体系结构非常的熟悉。HashMap本身就是不可排序的,但是该题偏偏让HashMap排序,那我们就得想在API中有没有这样的 Map 结构是有序的,我们不难发现其中LinkedHashMap就具有这样的结构,是链表结构有序的,更可喜的是他是 HashMap的子类,我们返回LinkedHashMap即可,还符合面向接口编程的思想。 

但凡是对集合的操作,我们应该保持一个原则就是能用JDK中的API就用JDK中的 API,比如排序算法我们不应该去用冒泡或者选择,而是首先想到用 Collections 集合工具类。 

import java.util.*; class HashMapTest { public static void main(String[] args) { HashMap users = new HashMap(); users.put(1, new User("张三", 25)); users.put(3,new User("李四",22)); users.put(2, new User("王五", 28)); System.out.println(users); HashMap sortHashMap = sortHashMap(users); System.out.println(sortHashMap); /** * 控制台输出内容 * {1=User [name=张三, age=25], 2=User [name=王五,age=28], 3=User [name=李四, age=22]} * {2=User [name=王五, age=28], 1=User [name=张三, age=25], 3=User [name=李四, age=22]} */ }  public static HashMap sortHashMap(HashMap map) { // 首先拿到 map 的键值对集合 Set entrySet = map.entrySet(); // 将 set 集合转为 List 集合,为什么,为了使用工具类的排序方法 List list = new ArrayList(entrySet); // 使用 Collections 集合工具类对 list 进行排序,排序规则使用匿名内部类来实现 Collections.sort(list, new Comparator() { @Override public int compare(Map.Entry o1, Map.Entry o2) { //按照要求根据 User 的 age 的倒序进行排 return o2.getValue().getAge() - o1.getValue().getAge(); } }); //创建一个新的有序的 HashMap 子类的集合 LinkedHashMap linkedHashMap = new LinkedHashMap(); //将 List 中的数据存储在 LinkedHashMap 中 for (Map.Entry entry : list) { linkedHashMap.put(entry.getKey(), entry.getValue()); } return linkedHashMap; }} class User { private String name; private int age;  public User(String name, int age) { this.name = name; this.age = age; }  public int getAge() { return age; }  public void setAge(int age) { this.age = age; }  public String getName() { return name; }  public void setName(String name) { this.name = name; }  @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; }}

2、请问 ArrayList、HashSet、HashMap 是线程安全的吗?如果不是怎么获取线程安全的集合?

通过以上类的源码进行分析,每个方法都没有加锁,显然都是非线程安全的。在集合中Vector 和HashTable是线程安全的。打开源码会发现其实就是把各自核心方法添加上了synchronized 关键字。Collections工具类提供了相关的 API,可以让上面那3个不安全的集合变为安全的。 

Collections.synchronizedCollection(c);

Collections.synchronizedList(list);

Collections.synchronizedMap(m);Collections.synchronizedSet(s); 

上面几个函数都有对应的返回值类型,传入什么类型返回什么类型。打开源码其实原理非常简单,就是将集合的核心方法添加上了synchronized关键字。 

3、ArrayList内部用什么实现的?

回答这样的问题,不要只回答个皮毛,可以再介绍一下ArrayList内部是如何实现数组的增加和删除的,因为数组在创建的时候长度是固定的,那么就有个问题我们往ArrayList中不断的添加对象,它是如何管理这些数组呢?通过源码可以看到ArrayList内部是用Object[]实现的。接下来我们分别分析ArrayList的构造以及add()、remove()、clear()方法的实现原理。 

● 无参数构造方法 

/** * Constructs a new {@code ArrayList} instance with zero initial capacity. */

public ArrayList(){  array=EmptyArray.OBJECT; } 

array 是一个 Object[]类型。当我们 new 一个空参构造时系统调用了 EmptyArray.OBJECT 属性,EmptyArray 仅仅是一个系统的类库,该类源码如下: 

public final class EmptyArray { private EmptyArray() { } public static final boolean[] BOOLEAN = new boolean[0]; public static final byte[] BYTE = new byte[0]; public static final char[] CHAR = new char[0]; public static final double[] DOUBLE = new double[0]; public static final int[] INT = new int[0]; public static final Class[] CLASS = new Class[0]; public static final Object[] OBJECT = new Object[0]; public static final String[] STRING = new String[0]; public static final Throwable[] THROWABLE = new Throwable[0]; public static final StackTraceElement[] STACK_TRACE_ELEMENT = new StackTraceElement[0];} 

也就是说当我们 new 一个空参 ArrayList 的时候,系统内部使用了一个 new Object[0]数组。 

● 带容量参数的构造器 

/** * Constructs a new instance of {@code ArrayList} with the specified * initial capacity. * @param capacity the initial capacity of this {@code ArrayList}. */

public ArrayList(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("capacity < 0: " + capacity); } array = (capacity == 0 ? EmptyArray.OBJECT : new Object[capacity]);} 

该构造函数传入一个 int 值,该值作为数组的长度值。如果该值小于 0,则抛出一个运行时异常。如果等于 0,则使用一个空数组,如果大于 0,则创建一个长度为该值的新数组。 

● 带集合参数的构造器 

/** * Constructs a new instance of {@code ArrayList} containing the elements of * the specified collection. * * @param collection the collection of elements to add. */

public ArrayList(Collection



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3