Class method with arguments returning an array

I am new to Java, not against the background of programming. I am doing a course and stuck on a piece, I hope it is appropriate to ask a question here). Ask about creating a method that takes an array of integers as argumetn and returns a sorted set containing the elements of this array. I do not include the code because I do not want an answer, but I would like to find the key. It drives me crazy!

Pending

x

+3
source share
6 answers

Ok, let it go together. Follow me:

Ask about creating a method that takes an array of integers as argumetn and returns a sorted set containing elements of an array.

We have three steps:

  • we need to figure out how to pass an array to a function
  • ,
  • , ( )

, , - , . divide et impera. , .

  • : , , . - ( ):
main() {     
    a[] = { "one", "two", "three"};
    f(a);
}

f(arr[]) {
    for ( int i = 0 ; i < arr.length ; i++ ) 
        print(arr[i]);
}

? , .

  1. : , . , . f() :
f(arr[]) {
     /* insert here your sorting method */
}

, . , , - :

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

, , - :

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

, . java first, .

:)

+5

:

  • , int ?
  • int?
  • .

SortedSet:

  • List. : asList()
  • List SortedSet. : addAll().

EDIT: Aaargh! SortedSet

+1
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;
        }        
    }

}
+1

, , , , .

!

0

, int. int . , . , .

, , .


, .

SortedSet, . : SortedSet, add addAll sortedSet. . Set

0

, :

SortedSet - , (: API " " )

"int" - , . (. Integer.valueOf()), Set.

The rest should be a simple iteration over the original array and put each element in a new set.

NTN

0
source

Source: https://habr.com/ru/post/1733320/


All Articles