37.数组
来源:互联网 发布:linux卸载软件包 编辑:程序博客网 时间:2024/06/05 18:53
1.数组的存储结构
(1)、存储基本数据类型的数组结构
public class TestPrimitiveArray { public static void main(String[] args) { //1.定义数组 int[] numbers; //2.分配内存空间 numbers = new int[4]; //3.为数组元素指定值 for(int i = 0;i < numbers.length;i++) { numbers[i] = i * 10; } } }
class Person { public int age; public String name; public void display() { System.out.println(name + "的年龄是: " + age); } } public class TestReferenceArray { public static void main(String[] args) { //1.定义数组 Person[] persons; //2.分配内存空间 persons = new Person[2]; //3.为数组元素指定值 Person p1 = new Person(); p1.age = 28; p1.name = "Miracle"; Person p2 = new Person(); p2.age = 30; p2.name = "Miracle He"; persons[0] = p1; persons[1] = p2; //输出元素的值 for(Person p : persons) { p.display(); } } }
2.一维二维数组
(1)一维数组
public class test { public static void main(String[] args){ int[] a1 = {100, 200, 150, 300};//int类型数组 //int a1[] = {100, 200, 150, 300};也可以 boolean[] a2 = {true, false, true};//boolean类型数组 String[] strs = {"AB", "AC"};//String类型数组 Object o1 = new Object(); Object o2 = new Object(); Object o3 = new Object(); Object[] objs = {o1, o2, o3};//Object数组 int[] a1 = new int[4];//动态初始化 } }
(2)二维数组
二维数组是一个特殊的一维数组,在这个一维数组中每一个元素都是“一维数组”
public class test { public static void main(String[] args){ int [][] a = { {1,2,3}, {45,2}, {0} }; System.out.println(a.length + "个一维数组"); //获取第一个一维数组 int[] a0 = a[0]; int a00 = a0[0]; System.out.println(a00); //获取最后一个一维数组中最后一个元素 System.out.println(a[a.length-1][a[a.length-1].length-1]); System.out.println(a[2][0]); //遍历二维数组 for(int i=0;i<a.length;i++){ for(int j=0;j<a[i].length;j++){ System.out.print(a[i][j]+ " "); } System.out.println(); } } }
(3)冒泡排序和选择排序
(4)Arrays
java.util.Arrays类能方便地操作数组,它提供的所有方法都是静态的。具有以下功能:
fill:给数组赋值
sort:对数组排序,按升序。
equals:比较数组,通过equals方法比较数组中元素值是否相等。
binarySearch:查找数组元素:通过binarySearch方法能对排序好的数组进行二分查找法操作。
package test2;import java.util.Arrays;public class Outer { public static void main(String[] args){ int[] a = {1,5,2,7,14,8,3} ; int[] b = new int [5]; Arrays.sort(a);//a从小到大排序 for(int i=0;i<a.length;i++) { System.out.println(a[i]); } System.out.println(Arrays.equals(a, b));//比较两个数组是否相等 System.out.println(Arrays.binarySearch(a, 1));//a数组中1的下标 Arrays.fill(a,2);//将a数组全部填充为2 for(int i: a) { System.out.println(a[i]); } }}
阅读全文
0 0
- 37.数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- js禁止enter回车事件方法
- Spring框架中ModelAndView、Model、ModelMap的区别
- [6-02]springaop
- 泛型编程之类模版
- 触类旁通,从400错误看Nginx常见故障与修复
- 37.数组
- DirectShow开发笔记与问题记录(2017.11.7更新)
- svn 命令
- 在编译项目的时候出现:Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.
- 机器学习中的特征选择
- 嵌入式linux QT环境搭建配置命令
- web.xml 配置
- Spring+Mybatis整合报错Mapped Statements collection does not contain value原因之一
- 程序构建原理