美文网首页
java数据结构

java数据结构

作者: ttyttytty | 来源:发表于2021-04-05 22:40 被阅读0次

变量

  • 局部变量:在栈上分配的,局部变量没有默认值,所以局部变量被声明后,必须经过初始化,才可以使用.
  • 实例变量具有默认值。
  • 类变量(静态变量)静态变量储存在静态存储区。经常被声明为常量,很少单独使用static声明变量。

8种基本数据类型

        boolean aBoolean = true;//1位
        byte anByte = 127;//8位
        char anChar = 65535;//16位Unicode 字符,0-65535(\u0000-\uffff)
        short aShort = 32767;//16位
        int anInt = 2147483647;//32位,默认
        long anLong = 222222222L;//64位
        float anFloat = 2.0f;//32位
        double andouble = 2.0;//64位
        //java的整型范围与运行的机器无关(平台不需要移植)     C/C++有关
        //java无无符号整型                                     C/C++有

基本类型包装类

        //所有的包装类(Integer、Long、Byte、Double、Float、Short)都是抽象类 Number 的子类。
        System.out.println("基本类型:byte 二进制位数:" + Byte.SIZE);
        System.out.println("最小值:Byte.MIN_VALUE=" + Byte.MIN_VALUE);
        System.out.println("最大值:Byte.MAX_VALUE=" + Byte.MAX_VALUE);
        System.out.println(Character.isLetter('s'));////char单个字符的包装类Character,Character.isLetter();
        BigDecimal bigDecimal = new BigDecimal(2.78);
        System.out.println(bigDecimal.toPlainString() + ",ROUND_HALF_UP with 1 scale:" + bigDecimal.setScale(1, BigDecimal.ROUND_HALF_UP));//多余小数点后位数限制时,进行四舍五入
        //位运算符是一位:&|~…^,>>>(高位补0),没有<<<,>>高位补符号位

BitSet

  • 大小会随需要增加,与ArrayList比,Vector 是同步访问的
BitSet bits1 = new BitSet(16);

常量(数值+字符(串))

        final int SOCRE = 2;
        final char NAME = '\u0001';
        final String TYPE = "\u0001";

引用数据类型

String

  • String,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。StringBuffer 用于线程安全,否则StringBuilder
        String anString = "abdu";//String 类有 11 种构造方法
        anString.concat("s");
        System.out.println(anString);//字符串不可变
        anString = anString + "s";
        System.out.println(anString);//字符串重指向
        String formatString = String.format("%s is %d", anString, anInt);
        System.out.println(formatString);
        StringBuffer stringBuffer = new StringBuffer("1323fs");
        stringBuffer.append("sssss");
        System.out.println(stringBuffer);//StringBuffer串可变
        stringBuffer.reverse();
        System.out.println(stringBuffer);
        stringBuffer.delete(0, 1);
        stringBuffer.insert(1, 222);
        stringBuffer.replace(1, 2, "358");
        System.out.println(stringBuffer);
        char[] dst = new char[10];
        stringBuffer.getChars(0, 2, dst, 0);
        System.out.println(dst);//复制字符串
        int index = stringBuffer.lastIndexOf("9", 4);
        System.out.println(index);
        //翻转字符串
        String reverStr = new StringBuilder(anString).reverse().toString();
        //字符串格式
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd   hh:mm:ss");
        String date = sDateFormat.format(new Date());
        String msg = date + "  ";
        System.out.println(msg);
        //String 数组
        String[] cateGory = new String[]{"姓名:", "年龄"};

复合数据类型

1.数组

        int[] anIntA = new int[8];
        int[] anIntArray = {1, 23};//其他基本数据的数组同理
        int[] anIntArr = new int[]{3, 1, 2, 6, 4, 2};
        //遍历
        for (int element : anIntArray) {
            System.out.println(element);
        }
        //java.util.Arrays 类能方便地操作数组,它提供的所有方法都是静态的(初始化/深拷贝/排序/搜索)
        int[] orig = new int[]{12, 23, 38};
        System.out.println(Arrays.toString(orig));
        Arrays.fill(anIntA, 77);
        System.out.println(anIntA.toString());
        int[] src = {1, 2, 3, 4, 5};
        int[] dest = new int[5];
        System.arraycopy(src, 0, dest, 0, 5);
        Arrays.copyOfRange(anIntA, 0, 3);
        int[] copyOne = Arrays.copyOf(orig, orig.length * 2);//扩容
        int[] copy2 = Arrays.copyOfRange(orig, 1, 6);
        System.out.println(Arrays.toString(copyOne));
        System.out.println(Arrays.toString(copy2));
        //排序
        Arrays.sort(copyOne);
        System.out.println(Arrays.toString(copyOne));
        int[][] aa = new int[][]{{1, 2}, {3, 4}, {2, 1}};
        Arrays.sort(aa, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return (o1[0] * o1[0] + o1[1] * o1[1]) - (o2[0] * o2[0] + o2[1] * o2[1]);
            }
        });
        //搜索
        int res = Arrays.binarySearch(copy2, 0, 2, 38);
        System.out.println(" Arrays.binarySearch" + res);
        //tostring
        int[][] tst = {
                {1, 3, 6},
                {3, 7},
                {2, 4, 0, 993}
        };
        System.out.println(Arrays.deepToString(tst));

2.类

  • 默认构造方法的访问修改符和类的访问修改符相同
  • 一个源文件中只能有一个public类.源文件的名称
  • 内部类、匿名类

3.接口

4.枚举

  • 枚举不可以继承其他类(final)
  • 枚举可以在构造处实现本枚举中的抽象方法

5.集合,遍历通过Iterator 接口(可以直接操作源数据的删插)或者foreach,比较通过定义Comparator接口

5.1Collection接口

        //        通用1:Collection排序
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(21, 2, 3));
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 < o2 ? -1 : o1 == o2 ? 0 : 1;
            }
        });
        System.out.println(list.toString());
        ArrayList<Integer> list1 = new ArrayList<>();
        Collections.fill(list, list1);    //浅拷贝
        System.out.println(list == list1);
        ArrayList list1 = new ArrayList();
        Collections.fill(list1, new Integer(0));//浅拷贝
        System.out.println(list1);
        Collections.sort(list1, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        Collections.emptyList();
        Collections.unmodifiableMap(new HashMap<>());
        Collections.singletonList(new ArrayList<>());

5.1.1 List接口

list1.add(new ListTestData(12, "12"));//add,内部item对象浅拷贝
list2.addAll(list1);//addAll,list深拷贝,内部item对象浅拷贝
list3 = list1;//=,list浅拷贝,内部item对象浅拷贝
list4 = (List<ListTest.ListTestData>) ((ArrayList<ListTest.ListTestData>) list1).clone();//clone,list深拷贝,内部item对象浅拷贝
5.1.1.1 ArrayList实现类
5.1.1.2 LinkedList实现类
        LinkedList<String> linkedList = (LinkedList<String>) Arrays.asList("1", "2", "1", "3");
        //                  双向链表,默认尾插,
        linkedList.add("1");//浅拷贝
        linkedList.addLast("2");
        linkedList.addFirst("0");
        linkedList.add(1, "5");//根据index,自动选择遍历的方向

        linkedList.remove();
        linkedList.removeFirstOccurrence("1");//默认
        linkedList.removeFirst();
        linkedList.removeLast();
        linkedList.removeLastOccurrence("1");
        //                  去除一个集合
        linkedList.removeAll((LinkedList<String>) Arrays.asList("2", "3"));//一个集合去除一个集合
        //Collections
        //                   初始化
        Collections.emptyList();
        List<Integer> menuList = Arrays.asList(1, 2, 3);
        List<Person> list = Arrays.asList(
                new Person("John", "Smith", "male"),
                new Person("Anna", "Martinez", "female"),
                new Person("Paul", "Watson ", "male")
        );
        //                                    批量填充
        List<Integer> fillList = new ArrayList<>(Collections.nCopies(5, 1));
        System.out.println(fillList);
        Collections.fill(fillList, 2);
        System.out.println(fillList);
        //                                    生成序列
        List<Integer> numbers = Stream.iterate(2, n -> n + 2)
                .limit(10)
                .collect(Collectors.toList());
        System.out.println(numbers);
        List<String> joinedNames = list.stream()
                .map(person -> person.getName().toUpperCase(Locale.ENGLISH))
                .collect(Collectors.toList());
        String joinedages = list.stream()
                .map(Person::getAge)
                .collect(Collectors.joining(", ")); // "John, Anna, Paul"
        String joined = String.join(";", list);
        //                                    根据对象某个属性排序
        peripheryNePlans.sort(Comparator.comparing(PeripheryNePlanVO::getPeripheryNeType)
                .thenComparing(PeripheryNePlanVO::getPeripheryNeName));
        //                                    获取对象列表的属性集合
        logicInterfaceIds = wpInterfaceVrf.stream()
                .filter(m -> m.getLogicNeCode().equals(logicNeCode))
                .map(WpInterfaceVrfPO::getLogicInterfaceType)
                .collect(Collectors.toList());
        //                                    从列表中获取满足条件的元素
        Set<String> toInitNeTypes = allNeTypes.stream()
                .filter(m -> !existTypes.contains(m)).collect(Collectors.toSet());
        //                                    反转list
        Collections.reverse(list);
        //                  将 list 转为 Map
        portInfoList.stream().collect(Collectors.groupingBy(p -> p.getPortTypeName().toUpperCase()));
        //                  删除removeIf或者iterator
        //                  排序                  
        list.stream().sorted(String::compareTo);
5.1.1.3 Vector
        Vector vector = new Vector();
        boolean result = vector.contains(1);
        int indexFind = vector.indexOf(1);
        vector.copyInto(anIntArray);
        anIntArray = (int[]) vector.toArray();
5.1.1.4 Stack<E> extends Vector<E>
        Stack<String> stringStack = new Stack<>();
        stringStack.push("w");
        String head = stringStack.peek();
        String out = stringStack.pop();

5.1.2 Set接口,无序非重复

5.1.2.1 TreeSet,排序的set
        TreeSet<Integer> guys = new TreeSet<>(Arrays.asList(1, 2, 3, 3, 6, 9));
//                                  二分查找最近元素
        System.out.println("TreeSet floor " + guys.floor(4));
        System.out.println("TreeSet ceiling " + guys.ceiling(4));

5.1.3 Queue接口

  • BFS层序遍历
5.1.3.1 LinkedList
  • public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
5.1.3.2 优先队列PriorityQueue
        Queue<Integer> priorityQueue = new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        //                          二维比较
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() {
            public int compare(int[] array1, int[] array2) {
                return array2[0] - array1[0];
            }
        });
5.1.3.3 阻塞队列ArrayBlockingQueue
        ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue(3);
        try {
            arrayBlockingQueue.put("q");//队列满了 阻塞
            arrayBlockingQueue.put("1");
            System.out.println(arrayBlockingQueue.take());//取q
            arrayBlockingQueue.put("q");
            System.out.println(arrayBlockingQueue.take());//取1,不取q,维护一个往后的index
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

5.2. Map(键/值对)接口,遍历用MapEntry

5.2.1 HashMap

        HashMap hashMap = new HashMap(guava.Maps.newHashMapWithExpectedSize(expect_size));//初始化大小
        Map<String, Integer> eachNum = new LinkedHashMap<>();// 依照放入顺序添加数据
        Map<String, String> map = new HashMap<>();
        map.put("key1", "112");
        map.put("key1", "22");//map.put自动更新
        map.put(null, null);//可以null-key,null-value
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "," + entry.getValue());
        }
        Map<String, List<Integer>> map1 = new HashMap<>();
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 3534, 7, 21, 3));
        map1.put("key-list", list);
        for (Map.Entry<String, List<Integer>> mapEntry : map1.entrySet()) {
            System.out.println(mapEntry.getKey() + "," + mapEntry.getValue().size());
        }
        private Map<String, List<NotifyInterface>> tables = new HashMap<String, List<NotifyInterface>>();    //复合类型
        //                      通过Iterator 接口遍历
        Iterator<String> iterator = (new ArrayList<String>()).iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            iterator.remove();
        }

5.2.2 LinkedHashMap

  • 有顺序 HashMap+LinkedList 底层额外维护了一个双向链表来维持数据有序. 可以通过设置accessOrder来实现FIFO(插入有序)或者LRU(true访问有序)缓存.
        Map<String, String> linkedHashM1ap = new LinkedHashMap<>(16, 0.75f, true);
        linkedHashM1ap.put("name1", "josan1");
        linkedHashM1ap.put("name2", "josan2");
        linkedHashM1ap.put("name3", "josan3");

5.2.3 HashTable

        Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(100, 0.5f);
        boolean isContained = hashtable.containsKey(2);
        String getResStr = hashtable.get(8);

转换

//转换  https://blog.csdn.net/PitBXu/article/details/97672145
        //int[]-》list
        int[] nums = new int[]{1, 23};
        List<Integer> integerArrayList = Arrays.stream(nums).boxed().collect(Collectors.toList());
        //对象数组->list
        System.out.println("array->list*********************************");
        String[] strArray = new String[]{"21", "33"};
        System.out.println("original array:" + Arrays.toString(strArray));
        //法1   不改变源
        ArrayList<String> list2 = new ArrayList<String>(Arrays.asList(strArray));
        System.out.println(list2.toString());
        list2.add("44");
        System.out.println(list2);
        System.out.println(Arrays.toString(strArray));
        //法2   不改变源
        ArrayList<String> arrayList = new ArrayList<String>(strArray.length);
        Collections.addAll(arrayList, strArray);
        System.out.println(arrayList.toString());
        arrayList.add("55");
        System.out.println(arrayList);
        System.out.println(Arrays.toString(strArray));
        //法3 不可变
        List<String> unmodifiedList = Arrays.asList(strArray);
//        unmodifiedList.add("w");//compile error :UnsupportedOperationException
        //list->数组
        System.out.println("list->array*********************************");
        List<String> lis2 = new ArrayList<>();
        lis2.add("1");
        lis2.add("2");
        Object[] toArray = lis2.toArray();//无参只能转为Object[]
        String[] array = lis2.toArray(new String[0]);
        System.out.println("list->数组 " + Arrays.toString(array));
        List<Integer> list11 = Arrays.asList(1, 2, 3);
        Integer[] a = new Integer[3];//不可int
        a = list11.toArray(a);
        String[] sarray = new String[]{"22", "12", "23"};
        ArrayList<String> listq = new ArrayList<>(Arrays.asList(sarray));
        String[] h = new String[listq.size()];
        listq.toArray(h);
        //list inilization
        List<String> personNames = new ArrayList<String>(10);
        List<Integer> integerList = new ArrayList<Integer>() {{
            add(11);
            add(22);
            add(33);
        }};
        List<String> stringList = new ArrayList<String>(Arrays.asList(new String[]{"a", "as", "d"}));
        //array to array
        int[] src1 = {1, 2, 3, 4, 5};
        int[] dest1 = new int[5];
        System.arraycopy(src1, 0, dest1, 0, 5);
        for (int s : dest) {
            System.out.println(s);
        }
        //list to array
        ArrayList<Integer> list3 = new ArrayList<Integer>() {{
            add(11);
            add(22);
            add(33);
        }};
        Integer[] array1 = list3.toArray(new Integer[list.size()]);
        for (Integer s : array1) {
            System.out.println(s);
        }
        //array to list
        String[] arrays = new String[]{"aa", "bb", "cc"};
        ArrayList<String> arrayList1 = new ArrayList<String>(Arrays.asList(arrays));
        for (String s : arrayList1) {
            System.out.println(s);
        }

去重

        //去重-1 stream
        ArrayList<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
        List<Integer> listWithoutDuplicatews = numbersList.stream().distinct().collect(Collectors.toList());
        //去重-2   LinkedHashSet
        LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(numbersList);
        ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);
        //去重-3  HashSet  不能保证添加顺序
        String[] ss = new String[]{"1", "2"};
        List<String> lists = new ArrayList<>(new HashSet<>(Arrays.asList(ss)));

  • 流不存储元素,不修改数据源
        //创建流
        Collection接口.stream()
        Stream<Object> stream = Stream.of();
        Stream.generate();
        Stream.iterate();
        Arrays.stream();
        //中间操作
        stream.filter(boolean);
        stream.flatMap();
        stream.map();
        //终止流
        stream.count();
        stream.forEach();
        //流转集合
        Object[] objects = stream.toArray();
        List<Object> collect = stream.collect(Collectors.toList());
        String collect1 = stream.collect(Collectors.joining(","));
        //基本类型流/IntegerStream

相关文章

网友评论

      本文标题:java数据结构

      本文链接:https://www.haomeiwen.com/subject/dixjkltx.html