声明一个整形数组,用冒泡法降序排列声明2个对象,加入到Arraylist中用增加for循环输出员工信息
时间: 2024-09-11 08:03:11 浏览: 83
声明一个整型数组并使用冒泡排序法进行降序排列,然后将两个对象添加到ArrayList中,最后使用for-each循环输出员工信息的步骤如下:
1. 声明一个整型数组:
```java
int[] numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
```
2. 使用冒泡排序算法对数组进行降序排列:
```java
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 0; j < numbers.length - 1 - i; j++) {
if (numbers[j] < numbers[j + 1]) {
// 交换两个元素的位置
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
```
3. 创建一个Employee类,并声明两个Employee对象:
```java
class Employee {
String name;
int age;
String department;
public Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", department='" + department + '\'' +
'}';
}
}
Employee emp1 = new Employee("张三", 30, "研发部");
Employee emp2 = new Employee("李四", 28, "市场部");
```
4. 将两个Employee对象添加到ArrayList中:
```java
ArrayList<Employee> employees = new ArrayList<>();
employees.add(emp1);
employees.add(emp2);
```
5. 使用for-each循环遍历ArrayList并输出员工信息:
```java
for (Employee employee : employees) {
System.out.println(employee);
}
```
阅读全文