《Java实战开发经典》第四章4.9

本文提供两种方法来找出数组中的最大值,并将其移至数组首位。第一种方法使用ArrayList存储数组元素,通过遍历找到最大值并调整位置;第二种方法利用Arrays.sort()函数对数组进行排序,直接获取最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package four;
import java.util.ArrayList;
import java.util.List;
//4.9将最大值保存在数组中的第一个位置
public class Night {
        public static void main(String[] args) {
            int temp=0;
            int i=0;
            int arr[]={77,12,3,4,6,90,100,2,6,2};
            List<Integer> alllist=new ArrayList<Integer>();//通过ArrayList方法实例化List集合
            //通过for循环求出数组中的最大值
            for(i=0;i<arr.length;i++){
                alllist.add(arr[i]);//将数组的内容全部添加到集合中
                if(arr[i]>temp){
                    temp=arr[i];
                }
            }   
            System.out.println("数组中的最大值为:"+temp);
            int x=alllist.indexOf(temp);//查找集合中指定元素的位置
            System.out.println(x);
            int y=arr[0];
            alllist.set(0,temp);//替换集合中指定位置的元素,0是集合中的位置,temp对应的被替换后的内容
            alllist.set(x,y);
            System.out.println("新的数组为:"+alllist);
        }

}



=====分割线,方法二======

import java.util.Arrays;

//定义一个整型数组保存10个数据,把最大值保存在数组中第一个元素的操作
public class Ninth {
    public static void main(String[] args) {
        int arr[]={1,2,3,4,5,6,7,8,9,10};
        Arrays.sort(arr);
        System.out.println("数组中的最大值为"+arr[9]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值