java9:一维数组的声明,创建,初始化(single-dimensional arrays)

Java数组声明与初始化详解
本文详细介绍了Java中数组的声明、定义与初始化过程,并通过实例演示了如何使用new操作符为数组分配空间,以及如何利用数组初始化语法简化代码。此外,还提供了一个完整的纸牌游戏示例程序,展示了数组在实际应用中的使用方法。

1 声明与定义:

在说数组之前,还是得先说下声明与定义:

 变量的定义(definition):用于为变量分配存储空间,还可以为变量指定初始值。在一个程序中,变量有且仅有一个定义;
 变量的声明(declaration):用于向程序表明变量的类型和名字。定义也是声明:当定义变量时我们声明了它的类型和名字。可以通过使用extern关键字声明变量名而不定义它。

也就是说,有分配空间的叫定义, 没分配空间的叫声明。

怎么理解 声明中说的”定义也是声明“,这说明声明包括定义。所以诸如int a;extern int a;之类的一定是声明。那是不是定义还要接着往下看;如果程序前面都没有出现过a这个变量,这时你要使用a,你必须让程序知道你要使用a这个变量了。这时候你写入int a;以前没有a这个变量的,现在程序为了记住它,就得为他分配空间,于是这是个定义。
    如果程序包含的其他文件里已经出现过a了,这证明程序已经为a分配内存,这时你要使用a就方便很多了。你只需要告诉程序,这个a在其他地方定义过了,于是你写入extern int a;
    对于int a;来说,它既是定义又是声明;对于extern int a;来说,它是声明不是定义。一般为了叙述方便,把建立存储空间的声明称定义,而不把建立存储空间的声明称为声明.

2 声明一个数组变量 Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array and specify
the array’s element type. Here is the syntax for declaring an array variable:
elementType[] arrayRefVar;

也就是说,为了在程序中能够使用数组,你首先要声明一个变量,该变量是数组的引用,然后同时声明数组的元素类型, 例如声明一个double类型的数组,则为 double [] myList;

这里要注意,我们这里声明的 mylist 他是一个引用,当我们声明 double [ ] myLis; 时候,我们并没有为该数组在内存中分配数组需要的空间,他仅仅分配了这个数组的引用的空间。用一个图来看

其实就跟我们在讲 int a; 既是声明又是引用一样,因为他是基本类型,所以我们这样声明时候同时也为a 分配了空间;但是因为数组变量是一个引用变量,所以我声明 double [ ] myList;时候,仅仅分配了该引用的空间,还没有分配数组的空间。

3 创建数组

 Unlike declarations for primitive data type variables, the declaration of an array variable does
not allocate any space in memory for the array. It creates only a storage location for the refer-
ence to an array. If a variable does not contain a reference to an array, the value of the variable
is null. You cannot assign elements to an array unless it has already been created. After an
array variable is declared, you can create an array by using the new operator with the follow-
ing syntax:

arrayRefVar = new elementType[arraySize];

This statement does two things: (1) it creates an array using new elementType[array-
Size]; (2) it assigns the reference of the newly created array to the variable arrayRefVar.

按照我们上面说的 当我们声明一个数组变量时候,我们仅仅分配了数组引用的空间,并且初始化为null, 我们通过new 可以来给数组分配空间。语法是:arrayRefVar = new elementType[arraySize];

这个过程做了两个事情 1) 分配了arraySize个连续的elementType空间,2)将该块连续空间的引用赋值给arrayRefVar ,例如 接着上面的 double [] myList;   我们可以创建一个 4个元素的数组  myList=new double[4];

所以现在内存图应该是这样:


我们可以将上面的两个步骤可以合在一起 即直接  double [ ]  myList=new double[4];

4 数组下标变量 Array Indexed Variables及数组初始化

The array elements are accessed through the index. Array indices are 0 based; that is, they
range from 0 to arrayRefVar.length-1. In the example in Figure 6.1, myList holds ten
double values, and the indices are from 0 to 9.
Each element in the array is represented using the following syntax, known as an indexed
variable:
arrayRefVar[index] 

这跟我们在其他语言中一样,数组的元素通过数组下标来访问,下标从0~ refvar.length-1; 

例如我们可以给我们刚刚分配的图初始化:

myList[0]=0;

myList[1]=1;

 myList[2]=2;

myList[3]=3;

另外,java中有简洁的击发,叫数组初始化

Java has a shorthand notation, known as the array initializer, which combines in one state-
ment declaring an array, creating an array, and initializing, using the following syntax:
elementType[] arrayRefVar = {value0, value1, ..., valuek};
For example,
double[] myList = {1.9, 2.9, 3.4, 3.5};
This statement declares, creates, and initializes the array myList with four elements, which is
equivalent to the statements shown below:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

也就是说  double [ ] myList={1.9,2.9,3.4,3.5}; 这样一个语句做了三件事情 1)声明了一个数组变量  2)创建了数组元素空间 3)初始化。

5 practice: 纸牌游戏

假设现在有一副牌52张牌,填着0~51;其中 0~12、13~25、26~38、39~51 分别表示13张黑桃、红桃、方块、梅花。现在现将牌打乱,然后从中挑出四张牌,carNumber/13表示该牌属于哪一种花色,carNumber%13 表示该牌在该花色中是第几张牌。

这里说一下,将牌打乱其实就是产生两个随机数下标,然后交换这两个下标对应的元素,这样就相当模拟了洗牌的过程。

public class DeckOfCard
{
	public static void main(String [] args)
	{
		int [] cards=new int[52];
		String[] suits={"Spandes","Hearts","Diamonds","Clubs"};
		String [] ranks={"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
		//数组初始化
		for(int i=0;i<cards.length;i++)
		{
			cards[i]=i;
		}
		//打乱牌
		for(int i=0;i<cards.length;i++)
		{
			int index=(int)(Math.random()*cards.length);//产生[0,52)之间一个随机数
			int temp=cards[i];
			cards[i]=cards[index];
			cards[index]=temp;
		}
		for(int i=0;i<cards.length;i++)
		{
			System.out.print(cards[i]+"  ");
			if((i+1)%10==0) System.out.println();
		}
		System.out.println();
		for(int i=0;i<4;i++)
		{
			int index=(int)(Math.random()*cards.length);
			String suit=suits[cards[index]/13];
			String rank=ranks[cards[index]%13];
			System.out.println("index="+index+" card="+cards[index]+" in suit="+suit+", in rank = "+rank);
		}
	}
}

运行结果:





1. List the six main biwise operators in C++ and explain the function of each. 2. Why cannot bitwise operations be applied to variables of floating-point type? 3. Explain the purpose of the << (left shift) and >> (right shift) operators. What is the typical effect on the decimal value of a number when it is shifted left by 1? Shifted right by 1? 4. Describe the process of using a mask to check the value of a specific bit within an
integer. 5. How can you use the bitwise AND operator (&) to check if a number is even or odd?
Explain the logic. 6. What is the difference between the logical AND (&&) and the bitwise AND (&)? Provide an example scenario for each. 7. Explain the purpose of the ~ (bitwise NOT) operator. What is the result of applying it to a mask, and how can this be useful? 1. What is the primary goal of program debugging? What types of errors can it help identify? 2. Describe the difference between Step Over (F10) and Step Into (F11) debugging commands. When would you choose one over the other? 3. What is the purpose of a breakpoint in planned debugging? How do you set and remove a breakpoint in Visual Studio? 4. Explain the utility of the "Watch" window compared to the "Autos" or "Locals" windows during a debugging session. 5. What is the key difference between the Debug and Release configurations when building a project? Why is it necessary to create a Release version after successful debugging? 6. List at least three types of files commonly found in a project&#39;s Debug folder and briefly state their purpose (e.g., *.pdb). 7. During debugging, you notice a variable has an incorrect value. How can you change its value during runtime to test a hypothesis without modifying the source code? 8. What command is used to exit the debug mode and stop the current debugging session? 1. What is an array in C++? List its three main characteristics. 2. How are array elements numbered in C++? What is the valid index range for an array declared as int data[25];? 3. Explain the difference between array declaration and initialization. Provide an example of each. 4. What is an initializer list? What happens if the initializer list is shorter than the array size? 5. How can you let the compiler automatically determine the size of an array during initialization? 6. What values do elements of a local array contain if it is declared but not explicitly initialized? How does this differ from a global array? 7. What is an array out-of-bounds error? Why is it dangerous, and what are its potential consequences? 8. How do you calculate the number of elements in an array using the sizeof operator?
Provide the formula. What is a significant limitation of this method? 9. Why is it impossible to copy the contents of one array into another using the assignment
operator (arrayB = arrayA;)? What is the correct way to perform this operation? 10. Why does comparing two arrays using the equality operator (arrayA == arrayB) not check if their elements are equal? How should array comparison be done correctly? 11. What does the name of an array represent in terms of memory? 1. What is a pointer in C++ and what are its two main attributes? 2. Explain the difference between the & and * operators when working with pointers. 3. Why is pointer initialization critical and what dangers do uninitialized pointers pose? 4. What is the fundamental relationship between arrays and pointers in C++? 5. How does pointer arithmetic work and why does ptr + 1 advance by the size of the pointed type rather than 1 byte? 6. What is the difference between an array name and a pointer variable? Why can&#39;t you increment an array name? 7. What are the differences between const int*, int* const, and const int* const? 8. How can you safely iterate through an array using pointers, and what are the boundary risks? 9. What is a null pointer and why should you check for nullptr before dereferencing? 10. How do you access array elements using pointer syntax, and how does the compiler translate arr[i] internally? 1. What is a multidimensional array? How is a two-dimensional array structured in memory? 2. Explain the concept of an "array of arrays". How does this relate to the declaration int arr/ROWS//COLS;? 3. The name of a two-dimensional array without indices is a pointer constant. What does this pointer point to? What do the expressions *(A + i) and *(*(A + i) +j) mean for a two-dimensional array A? 4. Describe the different ways to access the element A/1/[2/ of a two-dimensional array
using pointers. 5. What is the rule for omitting the size of dimensions when initializing and when passing a multidimensional array to a function? Why is it allowed to omit only the first dimension? 6. Explain the principle of "row-major order" for storing two-dimensional arrays in memory.
How does this affect element access? 7. Why are nested loops the standard tool for processing multidimensional arrays?
Describe the typical pattern for iterating through a matrix. 1. How is a character string stored in memory in C++? What is the role of the null terminator (10), and why is it critical for C-style strings? 2. Why must the size of a char array declared to hold a string be at least one greater than the number of characters you intend to store? 3. The array name without an index is a pointer constant. What does the name of a char array point to? 4. What are the two main ways to initialize a C-style string? What is a common mistake when using the initializer list method, and what is its consequence? 5. Why is it necessary to add _CRT_SECURE_NO_WARNINGS to the preprocessor definitions in Visual Studio when working with many standard C library functions?
What is the alternative approach? 6. What is the key difference between stropy and strncpy? Why might strncpy be considered safer? 7. How does the stremp function determine if one string is "less than" another? Why can&#39;t you use the == operator to compare two C-style strings for content equality? 8. Describe the purpose and parameters of the strok function. How do you get all tokens from a string? 9. What do the functions strchr and strrchr do? How do they differ? 10. Explain what the strstr function returns and what it is commonly used for. 11. What is the purpose of the functions in the < cctype> header? Give three examples of such functions and their use. 12. What is the difference between tolower(c) and_tolower(c)? When should you use each? 1. What is a function in C++? Name the three core benefits of using functions in a program. 2. What is the difference between a function declaration (prototype) and a function definition? Provide examples. 3. What is a function signature? Which elements are part of the signature, and which are not? 4. What methods of passing parameters to a function do you know? Explain the difference between pass-by-value, pass-by-pointer, and pass-by-reference. 5. Why can&#39;t you pass an array to a function by value? What is the correct way to pass an array to a function? 6. What is variable scope? How is it related to functions? 7. How does a function return a value? What happens if a function with a non-void return type does not return a value on all control paths? 8. Can you use multiple return statements in a single function? Provide an example. 9. What is function overloading? What is it based on? 10. How is interaction between functions organized in a program? Provide an example program with several functions. 11. What are default parameters? How are they specified, and in what cases are they useful? 12. How can you prevent a function from modifying the data passed to it? What modifiers are used for this? 13. What is recursion? Provide an example of a recursive function. 14. What common errors occur when working with functions? How can they be avoided? 15. How do you use pointers to functions? Provide an example of declaring and calling a function through a pointer.用中文解答,每个问题重复一遍题目
最新发布
11-23
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值