//声明
//int[] a;
int a[];
//申请空间,int数组默认初始值为0
a= new int[5];
//根据下标单个赋值初始化
a[0] = 2;
//循环赋值
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
//int [] c ={1,3,4,5,6};
//int c[] ={1,3,4,5,6};
int c[] = new int[]{1,3,4,5,6};
java.lang.Object
java.util.Arrays
package com.datastructure.test;
import java.util.Arrays;
import java.util.List;
public class ApiArray {
public static void main(String[] args){
int[] a = {4,6,78,8,34,56,26};
sortByApi(a);
}
/*
* 通过api直接对数组排序
*/
public static void sortByApi(int[] a){
System.out.println("排序前数组:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+"\t");
}
System.out.println();
Arrays.sort(a);
System.out.println("排序后数组:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+"\t");
}
}
}
排序前数组:
4 6 78 8 34 56 26
排序后数组:
4 6 8 26 34 56 78
package com.datastructure.test;
import java.util.Arrays;
import java.util.List;
public class ApiArray {
public static void main(String[] args){
int[] a = {4,6,78,8,34,56,26,2};
sortByBubble(a);
}
/*
* 冒泡排序
*/
public static void sortByBubble(int[] a){
int temp,i,j;
System.out.println("排序前数组:");
for (i = 0; i < a.length; i++) {
System.out.print(a[i]+"\t");
}
for (i = 1; i < a.length; i++) {
for (j = 0; j < a.length-i; j++) {
if (a[j]>a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
System.out.println();
System.out.println("排序后数组:");
for (i = 0; i < a.length; i++) {
System.out.print(a[i]+"\t");
}
}
}
for (i = 1; i < a.length; i++) {
for (j = 0; j < a.length-1; j++) {
if (a[j]>a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
str="hellomynameisAndy";
char [] charArray = str.toCharArray();
package com.datastructure.test;
public class Array {
public static void main(String[] args) {
StringToArray("1234");
}
/*
* 字符串转int数组,这里要求输入String全是数值
*/
public static void StringToArray(String str){
char[] ch;
int [] i;
int len;
//string长度
len = str.trim().length();
//初始化int数组
i=new int[len];
//通过charAt()取得单个字符转换成String类型再通过parseInt()转换成int类型
for (int j = 0; j < len; j++) {
i[j] =Integer.parseInt(String.valueOf(str.charAt(j)));
}
//int数组输出
System.out.println("int数组输出:");
for (int j = 0; j < i.length; j++) {
System.out.print(i[j]+"\t");
}
}
}
int a[][];
int [][] b;
int a[][];
a = new int[][]{{12,3,34},{23,34,56,78}};
int[][] c ={{1,2,3},{34,55,6},{45,678,89}};
int [][] b;
b=new int[2][3];
b[0][0] = 1;
b[0][1] = 2;
b[0][2] = 5;
b[1][0] = 10;
b[1][1] = 34;
b[1][2] = 35;
//计算多少行
array.length
//计算每行多少个元素
array[0].length
package com.datastructure.test;
public class TwoDimensionalArray {
public static void main(String[] args){
int row,col;
//注意初始化字符或字符串的时候记得加引号
int[][] c ={{1,2,3},{34,55,6},{45,678,89}};
//计算行数和列数,如果已知就用不着了
row = c.length;
col = c[0].length;
System.out.println("二维数组遍历输出:");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}
}
二维数组遍历输出:
1 2 3
34 55 6
45 678 89
文章:
Java数据结构与算法之学习路线
Java数据结构与算法之Array数组
Java数据结构与算法之LinkedList单链表