Java常用基础知识

1、简介

该篇文档记录了本人一些容易忽略的java基础知识,也是当做笔记吧

2、实例

2.1 迭代器遍历修改的问题

/**
 * 测试ForEach 遍历及修改的问题
 *
 * modCount是ArrayList的一个属性,继承自抽象类AbstractList,用于表示ArrayList对象被修改次数。
 * 整个ArrayList中修改modCount的方法比较多,有add、remove、clear、ensureCapacityInternal等,
 * 凡是设计到ArrayList对象修改的都会自增modCount属性。(和expectModeCount和modCount----关系很大,2者不等则会抛异常
 * 而 iterator.remove 则会进行修改
 * )
 */
public class TestForEach {
    public static void main(String[] args){
        List<String> mList = new ArrayList<>();
        mList.add("2");
        mList.add("1");
        System.out.println(mList);

        /*
        for (String str:mList){
            System.out.println(str);
            if ("1".equals(str)){
                mList.remove(str);(该方法问题,修改了modCount的数值)
            }
        }
        Exception in thread "main" java.util.ConcurrentModificationException
        */

        /*
          正确姿势使用迭代器的remove 方法
         */
        Iterator<String> listIterator = mList.iterator();
        while (listIterator.hasNext()){
            String node = listIterator.next();
            if ("1".equals(node)){
                listIterator.remove();
            }
        }
        System.out.println(mList);
    }
}

由于能力有限嘛,分析的不太好,大家可以看下这篇博主的讲解。java.util.ConcurrentModificationException 异常问题详解

小结:

使用迭代器遍历时,不得使用LIST的修改(remove add) 方法,而应当使用迭代器的 iterator.remove() 方法,进而可以使用修改 modCount 和 expectedCount一致。

        List<String> mList = new ArrayList<>();
        mList.add("0");
        mList.add("1");
        mList.add("2");
        mList.add("3");
        for (int i=0;i<mList.size();i++){
            if ( i==1){
                System.out.println("马上continue了");
                continue;
            }
            System.out.println(mList.get(i));
        }
    }
    
    /*  output
        0
        马上continue了
        2
        3
        */

另外补充一下: continue的用法是 结束本次循环,跳入下一次循环。

2.2 equals() 和 hashCode() 的用途

2.2.1 原始类

public class Man {
    private int age;
    private String name;

    public Man(int age, String name) {
        this.age = age;
        this.name = name;
    }

    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;
    }
}
        Man man1 = new Man(11,"小李");
        Man man2 = new Man(11,"小李");
        System.out.println(man1.equals(man2));
        // false

2.2.2 重写equals 方法 

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Man)){
            return false;
        }
        Man next =  (Man) obj;
        return next.age == age && next.name.equals(name);
    }
        Man man1 = new Man(11,"小李");
        Man man2 = new Man(11,"小李");
        System.out.println(man1.equals(man2));
        // true

 补充:当确定一个元素是否属于某个list,发现某个元素的索引,以及从某个list中移除一个元素时,都会调用equals 方法。

        List<Man> manList = new ArrayList<>(5);
        Man man1 = new Man(11,"小李");
        manList.add(man1);
        Man man2 = new Man(11,"小李");
        System.out.println(manList.indexOf(man2));
        // 0 

2.2.3  重写hashCode方法

应当明确的是 Set 或者说 List列表添加对象时,是通过鉴定该对象的hash值来判定是否相等的,进而添加入的,看下面这个结果。

都清楚,list添加的成员可重复而set是不可重复的,当然这个对象是有条件的撒。

未添加:

        Set<Man> manList = new HashSet<>();
        Man man1 = new Man(11,"小李");
        Man man2 = new Man(11,"小李");
        manList.add(man1);
        manList.add(man2);
        System.out.println(manList);
        // [eve_10_7.Man@610455d6, eve_10_7.Man@511d50c0]

已添加:看看效果呢,完美

    @Override
    public int hashCode() {
        return name == null?0:name.hashCode();
    }
        Set<Man> manList = new HashSet<>();
        Man man1 = new Man(11,"小李");
        Man man2 = new Man(11,"小李");
        manList.add(man1);
        manList.add(man2);
        System.out.println(manList);
        // [eve_10_7.Man@b8d1f]

 补充:这里list具体添加对象执行过程后续增加上。

  Person A = new Person("A");
  Person B = new Person("A");
  HashMap<Person,Integer> map = new HashMap<>();
  map.put(A,1);
  map.put(B,2);
  System.out.println(map);
  {A=2}
    /**
     * hashmap比较键的关键
     * @return
     */
    @Override
    public int hashCode() {
        return name == null?0:name.hashCode();
    }

2.3 常用注解

  @SuppressWarnings()  关闭不当的编译器警告信息

 一个注解必定包含 @Target 标示注解运用的地方(方法还是类)

                             @Retentation 标注注解运用的级别(源码 类文件 运行时)

【没有元素的注解称做 标记注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ShowName {
}

后续:未完待续,敬请期待!

2.4 静态方法及成员

静态方法以及成员能够被继承但不能够重写

2.5 移除List后几个元素

List<String> mList = new ArrayList<>();
mList.add("一");
mList.add("二");
mList.add("三");
mList.add("四");
mList.add("五");
mList.add("六");
mList.add("七");
mList.add("八");
System.out.println("       "+mList.toString());
int deleteSize = 4;
System.out.println("删除"+deleteSize+"后:");
for (int i=0;i<deleteSize;i++){
   mList.remove(mList.size()-1);
 }
System.out.println("       "+mList.toString());

2.6 关于扩容

这是vector的扩容,正常情况下是 n+x,当前数组长度的基础上再增加 长度+x 的容量,对于栈来说默认的因子是10

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

        if (o == null) {
            for (int i = index; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

2.7 将线性的数据组装成数形结构

public class PersonTreeManage {
    List<PersonNode> mOriginData;
    // 构建数据
    public void makeData(){
        mOriginData = new ArrayList<>();
        mOriginData.add(new PersonNode("延长科技公司",1,0));
        mOriginData.add(new PersonNode("部门1",2,1));
        mOriginData.add(new PersonNode("部门2",3,1));
        mOriginData.add(new PersonNode("部门3",4,1));
        mOriginData.add(new PersonNode("员工A",5,2));
        mOriginData.add(new PersonNode("员工B",6,3));
        mOriginData.add(new PersonNode("员工C",7,4));
        /**
         * 这是算法内容 通过2次循环确定父子关系....
         */
        for (int i = 0;i<mOriginData.size();i++){
               PersonNode preNode =  mOriginData.get(i);
            for (int j=i+1;j<mOriginData.size();j++){
                PersonNode nextNode = mOriginData.get(j);
                if (preNode.getId() == nextNode.getPid()){
                    // pre 是 next父亲设置关系
                    preNode.getChildren().add(nextNode);
                    nextNode.setParent(preNode);
                }else if (preNode.getPid() == nextNode.getId()){
                    preNode.setParent(nextNode);
                    nextNode.getChildren().add(preNode);
                }
            }
        }
    }

    public void display(){
        PersonNode personNode =  mOriginData.get(0);
        display(personNode);
    }

    public void displayChildrenName(){
        displayChildrenName(mOriginData.get(0));
    }

    private void displayChildrenName(PersonNode node){
        for (int i=0;i<node.getChildren().size();i++){
            System.out.println(node.getChildren().get(i).getName());
        }
    }

    private void display(PersonNode node){
        System.out.println(node.getName());
        for (int i=0;i<node.getChildren().size();i++){
            display(node.getChildren().get(i));
        }
    }
}

2.8 同步锁以及死锁

public class Ruunner1 implements Runnable{
    private static int times = 0;

    @Override
    public void run() {
        // 同步...如果不同步 由于非原子导致数据不是 1/2
        synchronized (this){
            times ++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("当前调用次数: "+times);
        }

    }
}
    public static void main(String[] args){
        Runnable runnable =  new Ruunner1();
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }

**死锁来咯**

public class DeathRunner implements Runnable {
    private int index = 0;
    // 注意锁住的得是static的变量啊
    private static Object o1 = new Object();
    private static Object o2 = new Object();
    public void setIndex(int index) {
        this.index = index;
    }

    @Override
    public void run() {
        if (index == 0){
            synchronized (o1){
                System.out.println("我持有了O1");
                try {
                    Thread.sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }
                synchronized (o2){
                    System.out.println("持有了02");
                }
            }
        }else {
            synchronized (o2){
                System.out.println("我持有了O2");
                try {
                    Thread.sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }
                synchronized (o1){
                    System.out.println("持有了01");
                }
            }

        }
    }
}
        DeathRunner deathRunner1 = new DeathRunner();
        deathRunner1.setIndex(0);
        DeathRunner deathRunner2 = new DeathRunner();
        deathRunner2.setIndex(1);
        new Thread(deathRunner1).start();
        new Thread(deathRunner2).start();

2.9 移位运算以及&运算

左移运算符用“<<”表示,是将运算符左边的对象,向左移动运算符右边指定的位数,并且在低位补零。其实,向左移n 位,就相当于乘上2 的n 次方

int mode_shift = 2;
int unspecified = 0 << mode_shift;  // 000 (二进制)
int exactly = 1 << mode_shift;      // 100
int at_most = 2 << mode_shift;      // 1000
int mode_mask = 0x3 << mode_shift;  // 1100
System.out.println("左移2位的结果:unspecified = "+unspecified+",exactly = "+exactly+",at_most = "+at_most+",mode_mask = "+mode_mask);
 // 左移2位的结果:unspecified = 0,exactly = 4,at_most = 8,mode_mask = 12

 两者都为1才为1 否则为0 

        int measureSpec = 0B1011;
        int mode = measureSpec & mode_mask;
        int size = measureSpec & ~mode_mask;
        int nextSpec = (mode & mode_mask) | (size & ~mode_mask);
        System.out.println("二进制0B111的 mode = "+mode+" = "+Integer.toBinaryString(mode)+",size = "+size+" = "+Integer.toBinaryString(size));
        System.out.println("还原spec = "+nextSpec+" = "+Integer.toBinaryString(nextSpec));
        // 二进制0B111的 mode = 8 = 1000,size = 3 = 11
        // 还原spec = 11 = 1011

 

其他:正数的补码反码都是其本身,负数的补码是符号位不变,其他位取反,再+1;负数的反码是符号位不变其他位取反

int a = 0B100;
System.out.println("~100 = "+Integer.toBinaryString(~a));
// ~100 = 11111111111111111111111111111011
System.out.println(Integer.toBinaryString(~a).length());
// 32
// 4 * 8 = 32 int类型4字节

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值