如何更改数组中的位置

时间:2015-11-01 00:25:24

标签: java

我有一个名为people的课程,我会跟踪50个人,他们的等级,姓名,年龄和顺序。然后我有一个名为rearrange的第二课,我必须改变int order的位置。所以它会改变顺序,就像位置0的订单1一样,将移动到第48位。我需要在不使用任何循环的情况下完成所有操作。

class people {
     int order[] = new int[50];
     for(int j=0; j<order.length; j++) {
        order[j] = "order" + j;
        System.out.print(order);
  }
}
class rearrange {
    // In here i need to change the position of the int order, and need to do this without using any loop.
}

1 个答案:

答案 0 :(得分:1)

不应该重新排列成为人们阶级的方法吗?通常为名词创建类,动词通常是类的函数或方法。并不是最好有一个班级&#34; Person&#34;并创建一个包含50个数组的数组,只需更改其索引即可更改其顺序?

考虑这样的事情:

public class Person //create Person class with the attributes you listed
{
    private int rank;
    private int age;
    private String name;

    public Person(int rank, int age, String name) //constructor
    {
        this.rank = rank;
        this.age = age;
        this.name = name;
    }
}

public class MainClass
{
    Person[] people = new Person[50]; //array of Persons, containing 50 elements

    public static void main(String[] args)
    {
        for(int i = 0; i < people.length(); i++)
        {
            people[i] = new Person(something, something, something); //give all the people some values, you'll have to decide what values you are giving them
        }

        //do something with the rearrange function here
    }

    public static void rearrange(int target, int destination) //this is just a "swap" function 
    {
        Person temp = people[destination];

        people[destination] = people[target];
        people[target] = temp;
    }
}