javaSE--手写自定义数组 + 小算法:统计单词出现的次数

本文介绍了一个名为SuperArray的自定义数组类,实现排序、连续添加(add)和删除元素功能。同时,通过Arithmitic类展示了哈希映射在字符串计数中的应用。
public class SuperArray {
    private int[] array;
    private int currentIndex = -1;

    public SuperArray(int size){
        array=new int[size];
    }

    public SuperArray(){
        this(10);
    }

    public void sort(){
        for (int i=0;i<currentIndex;i++){
            for(int j=0;j<currentIndex-i;j++){
                if(array[j]>array[j+1]){
                    int temp = array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                }
            }
        }
    }

    /**
     *
     * @param data
     * @return SuperArray返回值,可以连续的add,不用换行add了
     */
    public SuperArray add(int data){
        currentIndex++;
        if(currentIndex>=array.length){
            int[] temp =new int[array.length * 2];
            for(int i=0;i<array.length;i++){
                temp[i]=array[i];
            }
            array =temp; //★这里新数组覆盖给旧数组是可以的!!!
        }
        array[currentIndex]=data;
        return this;  //this是内存的那个对象
    }

    /**
     * 删除元素,本质是后面的所有元素直接前移,以覆盖达到删除目的
     * @param index
     */
    public void delete(int index){
        if(index<0 || index>currentIndex) return;
        for(int i=index;i<currentIndex;i++){  //
            array[i]=array[i+1];
        }
        currentIndex--;
    }

    public void print(){
        for(int i=0;i<=currentIndex;i++){
            System.out.print(array[i]+" ");  //println有换行哦!!
        }
    }

    public String arrayToStr(){
        String res = "";
        for(int i=0;i<=currentIndex;i++){
            if(i==currentIndex){
                res+=array[i];
            }else{
                res+=array[i]+",";  //★
            }
        }
        return res;
    }



    public static void main(String[] args) {
        SuperArray superArray = new SuperArray(2);
        superArray.add(1).add(2).add(3).add(1).add(2).add(3);
        System.out.println(superArray.arrayToStr());
    }

}

map的遍历方式:用Map.entry!

public class Arithmitic {

    public static void main(String[] args) {
        String cw ="haha haha hhh Ha Ha" +"aa bb AA bb bb dd";
        String s = cw.toLowerCase();

        String[] words =s.split(" ");
        HashMap<String,Integer> map =new HashMap<>();

        for (String word : words){
            if(map.containsKey(word)){
                map.put(word,map.get(word)+1);
            }else {
                map.put(word,1);
            }
        }

        for (Map.Entry<String,Integer> entry : map.entrySet()){
            System.out.println(entry.getKey()+" appeared "+entry.getValue()+"times");
        }
    }

}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值