Java高频知识合集(1)

    科技2025-05-24  32

    1、数组操作 (1)增 int[] array = {2,5,13,27,55,57,76,82,99};//建有序数组 Scanner input = new Scanner(System.in); System.out.println("请输入需要插入的值:"); int t = input.nextInt();//读取控制台输入的值 int i = array.length-2;//数组插入末尾默认补个0,所以array.length-2就是99的位置 for (; i >=0 ; i--) { if (array[i]>t){ array[i+1] = array[i]; }else{ break; } } array[i+1] = t; for (int i1 : array) { System.out.println(i1); } (2)删 优化前: int[] array = {2,5,13,27,55,57,76,82,99}; Scanner input = new Scanner(System.in); System.out.println("请输入需要删除的元素的值:"); int t = input.nextInt(); int i = 0; for (; i < array.length ; i++) {//先找 if (array[i]==t){ break; } } if (i==array.length){ System.out.println(t+"不存在"); }else{ for (int j = i; j < array.length-1; j++) { array[j] = array[j+1]; } array[array.length-1] = 0;//切记 System.out.println("删除"+t+"成功"); for (int i1 : array) { System.out.println(i1); } } 优化后: boolean start = false;//假设找不到 for (int i = 0; i < array.length-1; i++) { if (start){//找到 array[i] = array[i+1]; }else{//没找到 if (array[i]==t){//先执行else操作,找到就改为true start = true; } } } if (start){ array[array.length-1] = 0; for (int i : array) { System.out.println(i); } }else{ System.out.println("不存在"+t); } 2、排序法 生成随机数组: Random rand = new Random(); int[] array = new int[10]; int size = 0; array[size++] = 1+rand.nextInt(100); boolean no; for (int i; size < array.length;) { i = 1+rand.nextInt(100); no = true; for (int j = 0; j < size; j++) {//判断10个随机数各不相同 if (array[j]==i){ no = false; break; } } if (no){//生成了不同的随机数则添加 array[size++] = i; } } 冒泡法: for (int i = 0,item; i < array.length-1; i++) { for (int j = 0; j < array.length-1-i; j++) { if (array[j]>array[j+1]){//两两比较,每当满足条件就需要交换一次 item = array[j]; array[j] = array[j+1]; array[j+1] = item; } } } for (int i = 0; i < array.length; i++) { System.out.println("排序后:"+array[i]); } 插入排序法: for (int i = 1,t,j=0; i < array.length; i++) { if (array[i]>=array[i-1]){ continue; } t = array[i]; for (j = i-1; j >=0 && t<array[j]; j--) { array[j+1] = array[j]; } array[j+1] = t; } for (int i : array) { System.out.println("排序后:"+i); } 选择排序: for (int i = 0; i < array.length-1; i++) { int maxValueIx = 0; int maxIx = array.length-1-i; for (int j = 1; j <= maxIx; j++) { if (array[maxValueIx]<array[j]){ maxValueIx = j; } } if (maxValueIx != maxIx){//每一轮循环只需要交换一次 int t = array[maxIx]; array[maxIx] = array[maxValueIx]; array[maxValueIx] = t; } } for (int i : array) { System.out.println(i); } 快速排序: public static void quick_sort(int s[],int l, int r) { if (l < r) { //Swap(s[l], s[(l + r) / 2]); //将中间的这个数和第一个数交换 参见注1 int i = l, j = r, x = s[l]; while (i < j) { while(i < j && s[j] >= x) // 从右向左找第一个小于x的数 j--; if(i < j) s[i++] = s[j]; while(i < j && s[i] < x) // 从左向右找第一个大于等于x的数 i++; if(i < j) s[j--] = s[i]; } s[i] = x; quick_sort(s, l, i - 1); // 递归调用 quick_sort(s, i + 1, r); } } 3. 面对对象特征(封装、继承(组合)、多态+案例演示) (1)封装 广义封装 模块封装 remote封装(EJB) EJB概述:EJB是sun的服务器端组件模型, 用EJB技术部署的分布式系统可以不限于特定的平台 其特点包括网络服务支持和核心开发工具(SDK) 狭义封装 权限封装 public protected default private 包封装(3-6层) 3层:到包名 4层:到业务模型 5层:包名+依赖工具+业务接口 6层:包名+依赖工具+中间键+业务接口 get\set数据封装 接口封装:暴露功能,屏蔽实现 (2)继承 单根继承,多实现 无法继承: 构造器和私有方法 不同包父类受protected类型无法继承 特殊词汇作用: final:加在属性上:属性值不可变 加在方法上:不可在子类中重写 加在类上:不能被继承,和abstract相反 加在包上:空包 finally:同常放在try。。。catch后,多用于资源的释放 finally中的代码只要jvm不关闭则都可执行 finalize:Object中定义的方法,finalize方法用于在垃圾收集器将 对象从内存中清除出去之前做清理工作,在垃圾收集器 销毁对象时调用,通过重写可以整理系统资源或者执行 其他清理工作 this: 指代不同:指当前对象的引用,应该为构造函数中的第一条语句,可以出现在非静态方法或代码块中 调用函数不同:可以实现当前类中的一个构造方法中调用其他同参的构造方法 引用对象不同:this.当前对象名 super: 指代不同:指当前对象bai里面du的父对象的引zhi用 调用函数不同:调用基类中的某一个构造函数(应该为构造函数中的第一条语句) 引用对象不同:引用当前对象的直接父类中的成员 static:加在属性上:由类创建的所有的对象,都共用这一属性 类变量的加载早于对象 类变量存放在静态域中 加在方法上:JVM启动时装载字节码文件过程中创建所有静态内容,仅一份 类方法内部可以调用静态的属性和静态的方法,而不能调用非静态的属性和方法 但是,非静态方法可以调用静态的属性和方法 加在类上: 普通类是不可以被静态修饰的,只有内部类可以 无需对象,通过类名就可以访问 (3)多态 形式: 重写:同一个类中名称相同参数不同(参数类型不同,个数不同,顺序不同)的方法 重载:子类重写与父类同名,同参,同返回值的方法 解释: 上转型(转父)小转大: 自动类型装换:父类引用指向子类对象Student stu = new KBStudent(); 下转型(转子)大转小: 强制类型转换:通过instanceof运算符判定父类引用指向子类对象的实际类型

    4、集合

    Collection的方法: add(Object o):增加元素 addAll(Collection c):... clear():... contains(Object o):是否包含指定元素 containsAll(Collection c):是否包含集合c中的所有元素 iterator():返回Iterator对象,用于遍历集合中的元素 remove(Object o):移除元素 removeAll(Collection c):相当于减集合c retainAll(Collection c):相当于求与c的交集 size():返回元素个数 toArray():把集合转换为一个数组 TreeSet的方法: first():返回第一个元素 last():返回最后一个元素 lower(Object o):返回指定元素之前的元素 higher(Obect o):返回指定元素之后的元素 subSet(fromElement, toElement):返回子集合 List的方法: add(int index, Object o):在指定位置插入元素 addAll(int index, Collection c):... get(int index):取得指定位置元素 indexOf(Obejct o):返回对象o在集合中第一次出现的位置 lastIndexOf(Object o):... remove(int index):删除并返回指定位置的元素 set(int index, Object o):替换指定位置元素 subList(int fromIndex, int endIndex):返回子集合 Queue的方法: boolean add(E e) : 将元素加入到队尾,不建议使用 boolean offer(E e): 将指定的元素插入此队列(如果立即可行且不会违反容量限制),当使用有容量限制的队列时,此方法通常要优于 add(E),后者可能无法插入元素,而只是抛出一个异常。推荐使用此方法取代add E remove(): 获取头部元素并且删除元素,不建议使用 E poll(): 获取头部元素并且删除元素,队列为空返回null;推荐使用此方法取代remove E element(): 获取但是不移除此队列的头 E peek(): 获取队列头部元素却不删除元素,队列为空返回null ArrayDeque和Deque的方法: addFirst(Object o):元素增加至队列开头 addLast(Object o):元素增加至队列末尾 poolFirst():获取并删除队列第一个元素,队列为空返回null poolLast():获取并删除队列最后一个元素,队列为空返回null pop():“栈”方法,出栈,相当于removeFirst() push(Object o):“栈”方法,入栈,相当于addFirst() removeFirst():获取并删除队列第一个元素 removeLast():获取并删除队列最后一个元素

    (3)ArrayList

    添加: public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } public void add(int index,E element){ rangeCheckForAdd(index); ensureCapacityInternal(size+1); System.arraycopy(elementData,index,elementData,index+1,size-index); elementData[index] = element; size++; } public boolean addAll(Collection<? extends E>c){ Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size+numNew); System.arraycopy(a,0,elementData,size,numNew); size += numNew; return numNew !=0; } public boolean addAll(int index,Collection<? extends E>c){ rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size+numNew); int numMoved = size-index; if(numMoved > 0){ System.arraycopy(elementData,index,elementData,index+1,numMoved) System.arraycopy(a,0,elementData,index,numNew); size += numNew; return numNew != 0; } } 删除: public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; } public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; } (3)HashMap代码 package kb08.util.map; import com.sun.org.apache.xpath.internal.operations.Bool; import kb08.util.Iterator; import kb08.util.List; import kb08.util.Map; import kb08.util.array.ArrayList; import kb08.util.link.LinkedList; public class HashMap<K,V> implements Map<K,V> { private static final int DEFAULT_CAPACITY = 16;//默认容量 private static final float EXPAND_FACTOR = 0.75f;//扩容因子 private static final float REDUCE_FACTOR = 0.25F;//收缩因子 private static final Object[] EMPTY = {}; private float expandFactor; private Object[] elementDate;//数据数组 private int size; public HashMap(){ this(DEFAULT_CAPACITY,EXPAND_FACTOR); } public HashMap(int capacity,float expandFactor){//用户自定义扩容因子和容量要满足一下范围,只是进行初始化 initElementData(capacity); this.expandFactor = expandFactor<=0.5 || expandFactor>=0.75 ? EXPAND_FACTOR : expandFactor; //输入一个扩容因子和EXPAND_FACTOR进行比较 } private void initElementData(int capacity){ elementDate = capacity<=1 ? EMPTY : new Object[Integer.highestOneBit(capacity-1)<<1]; } /** * 判定什么时候需要扩容 * @return -1:缩 0:不变 1:扩 */ private int needChange(){ double factor = size*1.0/elementDate.length; return factor>=expandFactor ? 1 : factor<=REDUCE_FACTOR ? -1 : 0; } private void expand(){ change(true); } private void reduce(){ change(false); } //扩容:散列均匀,减少链表的数量和长度 private void change(boolean expand){ Object[] copy = elementDate;//备份 size = 0; initElementData(expand ? elementDate.length<<1 : elementDate.length>>1); for (Object o : copy) { if (null==o){ continue; } if (o instanceof Entry){ put((Entry<K, V>) o); continue; } Iterator<Entry<K, V>> it = ((LinkedList<Entry<K, V>>) o).iterator(); while (it.hasNext()){ put(it.next()); } } } @Override public int size() { return size; } @Override public boolean isEmpty() { return 0==size; } @Override public boolean containsKey(K key) { return null != _get(key); } @Override public boolean containsValue(V value) { Iterator<V> it = values().iterator(); while (it.hasNext()){ V v = it.next(); if (value == v || (null!=value && value.equals(v)) || (null!=v && v.equals(value))){ return true; } } return false; } private Entry<K,V> _get(K key){ int index = index(key); Object o = elementDate[index]; Entry<K,V> e = null; if (null!=o){ if (o instanceof Entry){ e = (Entry<K,V>)o; }else{ Iterator<Entry<K,V>> it = ((LinkedList<Entry<K,V>>)o).iterator(); while (it.hasNext()) { if (key.equals(it.next().getKey())){ e = it.next(); break; } } } } return e; } @Override public V get(K key) { Entry<K,V> e = _get(key); return null == e ? null : e.getValue(); } private int index(K key){ return null==key ? elementDate.length-1 : key.hashCode()%(elementDate.length-1); } private V put(Entry<K,V> entry){ if (1==needChange()){ expand(); } int index = index(entry.getKey()); Object o = elementDate[index]; V v = null; boolean noRepeat = true; if (null==o){ elementDate[index] = entry; }else if (o instanceof Entry){ Entry<K,V> e = (Entry<K,V>) o;//e是旧值 if (null==e.getKey() || e.getKey().equals(entry.getKey())){ v = e.getValue(); e.setValue(entry.getValue()); noRepeat = false; }else { LinkedList<Entry<K,V>> list = new LinkedList<>(); list.add(e); list.add(entry); elementDate[index] = list; } }else { LinkedList<Entry<K, V>> list = (LinkedList<Entry<K, V>>) o; Iterator<Entry<K,V>> it = list.iterator(); while (it.hasNext()){ Entry<K,V> e = it.next(); if (e.getKey().equals(entry.getKey())){ v = e.getValue(); e.setValue(entry.getValue()); noRepeat = false; break; } } if (noRepeat){ list.add(entry); } } if (noRepeat){ size++; } return v; } @Override public V put(K key, V value) { return put(new Entry<>(key,value)); } @Override public V remove(K key) { if (needChange()==-1){ reduce(); } int index = index(key); Object o = elementDate[index]; V v = null; boolean exist = false; if (null != o){ if (o instanceof Entry){ v = ((Entry<K,V>)o).getValue(); elementDate[index] = null;//数组删除:提出元素后返回null exist = true; }else{ LinkedList<Entry<K, V>> list = (LinkedList<Entry<K, V>>) o; Iterator<Entry<K, V>> it = list.iterator(); while (it.hasNext()){ Entry<K, V> e = it.next(); if (e.getKey().equals(key)){ it.remove();//链表删除:remove v = e.getValue(); exist = true; break; } } if (exist && list.size()==1){ elementDate[index] = list.get(0); } } } if (exist){ size--; } return v; } @Override public List<K> keys() { List<K> list = new ArrayList<>(size);//把获取的键值放在数组中 for (Object o : elementDate) { if (null==o){ continue; } if (o instanceof Entry){ list.add(((Entry<K,V>)o).getKey()); }else { Iterator<Entry<K,V>> it = ((LinkedList<Entry<K,V>>)o).iterator(); while (it.hasNext()){ list.add(it.next().getKey()); } } } return list; } @Override public List<V> values() { List<V> list = new ArrayList<>(size); Iterator<K> it = keys().iterator(); while (it.hasNext()){ list.add(get(it.next())); } return list; } @Override public List<Entry<K, V>> entries() { List<Entry<K, V>> list = new ArrayList<>(size); Iterator<K> it = keys().iterator(); while (it.hasNext()){ list.add(_get(it.next())); } return list; } }
    Processed: 0.011, SQL: 8