Java 程序,将 ArrayList 转换为字符串,反之亦然
在本文中,我们将了解如何将 arrayList 转换为字符串,反之亦然。ArrayList 类是一个可调整大小的数组,可以在 java. util 包中找到。Java 中内置数组和 ArrayList 之间的区别在于,不能修改数组的大小。
以下是相同内容的演示:
假设我们的输入是 −
Input string: Java Program
期望的输出应该是 −
The array after conversion from string is: J a v a P r o g r a m
算法
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Create an array and add elements to it using the ‘add’ method. Step 5 - Display the list on the console. Step 6 - Create another empty array of previous array size. Step 7 - Convert it into string using the ‘toString’ method. Step 8 - Iterate over the elements and display the elements on the console. Step 9 - Stop
示例 1
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
ArrayList input_array= new ArrayList<>();
input_array.add("Java");
input_array.add("Python");
input_array.add("Scala");
input_array.add("JavaScript");
System.out.println("The array is defined as: " + input_array);
String result_string = input_array.toString();
System.out.println("\nThe result string is: " + result_string);
}
}输出
The required packages have been imported The array is defined as: [Java, Python, Scala, JavaScript] The result string is: [Java, Python, Scala, JavaScript]
示例 2
这里,我们将字符串转换为一个数组。
public class Demo {
public static void main(String args[]){
String input_string = "Java Program";
System.out.println("The string is defined as: " + input_string);
char[] result_array = new char[input_string.length()];
for (int i = 0; i < input_string.length(); i++) {
result_array[i] = input_string.charAt(i);
}
System.out.println("The array after conversion from string is: " );
for (char c : result_array) {
System.out.print(c + " ");
}
}
}输出
The string is defined as: Java Program The array after conversion from string is: J a v a P r o g r a m
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP