简体   繁体   English

具有返回数组的参数的类方法

[英]Class Method with arguments that returns an array

I'm pretty new to Java and not from a programming background. 我对Java很陌生,而不是来自编程背景。 I am doing a course and am stuck on a piece I hope this is appropriate to ask a question here). 我正在上一门课程,并且被困在一块上,希望这适合在这里提问。 The question ask to create a method that takes an array of integers as an argumetn and returns a sorted set containing the elements of the that array. 问题要求创建一个方法,该方法将整数数组作为argumetn,并返回包含该数组元素的排序集。 I am not including the code as I don't want the answer but I would like a clue. 我不包含代码,因为我不想要答案,但是我想要一个线索。 It's driving me nuts! 真让我发疯!

Yours in anticipation 您的期待

JC 杰西

Ok, let's go through this together. 好吧,让我们一起经历一下。 Follow me: 跟着我:

The question ask to create a method that takes an array of integers as an argumetn and returns a sorted set containing the elements of the that array. 问题要求创建一个方法,该方法将整数数组作为argumetn,并返回包含该数组元素的排序集。

We have three steps here: 这里有三个步骤:

  1. we need to figure out how to pass an array to a function 我们需要弄清楚如何将数组传递给函数
  2. we need to figure out how to sort elements 我们需要弄清楚如何对元素进行排序
  3. we need to figure out how to return an array (of sorted elements) 我们需要弄清楚如何返回一个数组(包含排序元素)

What I'm doing here is taking the main problem and dividing it into smaller, more approachable sub-problems. 我在这里正在做的是解决主要问题并将其分解为更小的,更易于解决的子问题。 It's called divide et impera . 这就是所谓的Divet et Impera You'll encounter this approach very often if you pursue a programming career. 如果您从事编程职业,就会经常遇到这种方法。

  1. pass an array to a function: write a simple program that prepares an array, passes it to a function and have the function print it. 将数组传递给函数:编写一个简单的程序,准备一个数组,将其传递给函数并让函数打印它。 Something like (in my own just-made up version of a pseudocode): 类似于(在我自己的伪代码的伪造版本中):
 main() { a[] = { "one", "two", "three"}; f(a); } f(arr[]) { for ( int i = 0 ; i < arr.length ; i++ ) print(arr[i]); } 

You with me so far? 到目前为止,你和我在一起吗? I hope so. 希望如此。

Now, 现在,

  1. sorting of elements: I'm pretty sure you already have a way of doing it in your textbook or your notes. 元素排序:我很确定您已经在教科书或笔记中找到了一种方法。 Remember you must sort an array. 请记住,您必须对数组进行排序。 Now our function f() would look something like: 现在我们的函数f()看起来像:
 f(arr[]) { /* insert here your sorting method */ } 

Once this is done, you need to pass back this array to the main function. 完成此操作后,您需要将此数组传递回main函数。 Now, if you were to pass back a single value from a function, you would do something like: 现在,如果要从函数传回单个值,则应执行以下操作:

 int g() { int i = 0; i++; return i; } 

since they want you to return an array, it would be something like: 因为他们希望您返回一个数组,所以它类似于:

 int[] h() { /* initialize the array */ int[] j = { 1, 2, 3 }; /* your code goes here */ return j; } 

At this point you have all elements you need for the question you were asked. 至此,您已经具备了提出问题所需的所有要素。 Just make them work in java first , then put everything together. 只需使其首先在Java中工作,然后将所有内容放在一起即可。

Welcome to the magic world of programming :) 欢迎来到神奇的编程世界:)

Tips: 提示:

  1. How do you create an element that takes an int as an argument? 如何创建一个以int作为参数的元素?
  2. How do you declare an array of type int ? 如何声明int类型的数组?
  3. Put those together. 将它们放在一起。

For the SortedSet : 对于SortedSet

  1. Convert the array to a List . 将数组转换为List Hint: look for an asList() method 提示:寻找一个asList()方法
  2. Add all the elements of the resulting List to a SortedSet . 将结果List所有元素添加到SortedSet Hint: addAll() . 提示: addAll()

EDIT: Aaargh! 编辑: Aaargh! Didn't see the SortedSet in the question 在问题中没有看到SortedSet

import org.junit.Test;

import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * @version $Id$
 */
public class MainTest {

    public SortedSet sortIntegers(Integer[] ints) {
        return new TreeSet(Arrays.asList(ints));
    }

    @Test
    public void it_should_return_a_sorted_set() throws Exception {
        assertThat(sortIntegers(new Integer[]{5, 7, 1, 6}), is(instanceOf(SortedSet.class)));
    }

    @Test
    public void it_should_return_four_elements() throws Exception {
        assertThat(sortIntegers(new Integer[]{5, 7, 1, 6}).size(), is(4));
    }

    @Test
    public void it_should_return_in_the_right_order() throws Exception {
        Integer previous = 0;

        for (Integer current : sortIntegers(new Integer[]{5, 7, 1, 6})) {
            assertThat(current , is(greaterThan(previous)));
            previous = current;
        }        
    }

}

There are plenty of tutorials on the net, check out this example , its not exactly what you want but may point you in the right direction. 网上有很多教程,请查看此示例 ,它不完全是您想要的,但可能会为您指明正确的方向。

Good Luck! 祝好运!

You can create a new array, and iterate over your given array as long as there are still ints in your array. 您可以创建一个新数组,并在给定数组上进行迭代,只要您的数组中仍然有整数。 You can search for the highest or lowest int and put this one in the new array, and remove it from the given array. 您可以搜索最高或最低的int并将其放入新数组中,并将其从给定的数组中删除。 You can do this as long as there are items in the given array. 只要给定数组中有项目,就可以执行此操作。 If the given array is empty return the new array. 如果给定数组为空,则返回新数组。

I thought this is what you meant. 我以为你是这个意思


I did not read properly, sorry. 我没有正确阅读,对不起。

You can create a new SortedSet, see here for more information: SortedSet , and use add or addAll to add items to this sortedSet. 您可以创建一个新的SortedSet,有关更多信息,请参见此处: SortedSet ,并使用add或addAll将项目添加到此sortedSet中。 See for more information about Set 请参阅有关Set的更多信息

There are some points you should remember: 您应该记住一些要点:

SortedSet is an interface, so you must find a suitable implementation (Hint: the API contains "All Known Implementing Classes") SortedSet是一个接口,因此您必须找到合适的实现(提示: API包含“所有已知的实现类”)

The "int"s are native datatypes, no objects. “ int”是本机数据类型,没有对象。 So you need to encapsulate them in wrappers (see Integer.valueOf() ) before you can use them in a Set. 因此,您需要先将它们封装在包装器中(请参阅Integer.valueOf() ),然后才能在Set中使用它们。

The rest should be a simple iteration over the source array, and putting each element to the new Set. 其余的应该是对源数组的简单迭代,并将每个元素放入新的Set中。

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM