2013-06-18 2 views
-3

배열을 반환하는 메서드를 만들면 궁금합니다. 어떻게하면 주 또는 다른 방법으로 해당 배열의 특정 지점에 액세스 할 수 있습니까? 액세스하려고하는 경우배열의 특정 지점에 다른 방법으로 액세스하는 방법

int [] myArray = yourClass.deleteElement(thing, target) 
yourClass.test(myArray); 

:

예를 들어

: 당신이 다른 방법으로 배열을 전달하려는 경우

public static int[] deleteElement(int[]thing, int target){ 
int[]newThing; 

newThing=thing; 
int y=0; 
for (int i=0; i<thing.length; i++){ 
    if (thing[i]==target){ 
    newThing[y]=thing[i+1];} 
    y++; 
    } 

return newThing; 

} 



public static int test(int[]someArray){ 


    //here how can i access newThing[i]? 

    } 

감사 무리

+0

??? 너는 그것에 접근했다. 문제가 무엇입니까? –

+0

질문이 분명하지 않습니다. 다른 메소드가 같은 클래스의 멤버입니까? deleteElement()의 호출자입니까? 어레이에 언제 접속하고 싶습니까? 그리고 알려진 색인에 액세스하는 색인입니까? – Elist

답변

0

당신은 그것을 좋아합니까 그런 다음 지정하는 것과 같은 방식으로 지정합니다.

elementYouWantToAccess = 2 //or 3, or 6, or whatever element you want 
someArray[elementYouWantToAccess]; 

기술적으로 다음과 같이 말할 수 있습니다.

someArray[1]; //this would access the element at position 1

당신이하고있는 모든 것은 i가 요소 위치를 나열하고 있습니다. 배열은 위치를 선택하여 액세스 할 수 있습니다. 당신은 당신이 원하는 정확한 요소를 알 수없는 경우

, 당신과 같이 전체 배열을 반복 할 수 있습니다 당신이 원하는 요소를 찾을 때까지

public static int test(int[]someArray){ 

    for(int i=0; ii < someArray.length; i++){ 
     if(someArray[i] == someCondition){ 
     //do something to someArray[i] 
     } 
    } 

} 

는 다음 변수에 할당하거나 할 네가 원하는대로.

0

int[]을 반환하는 deleteElement(int[]thing, int target)으로 전화해야합니다. 메서드 내부에서 선언되었으므로 은 deleteElement(int[]thing, int target) 외부에 액세스 할 수 없습니다. 그래서 :

int[] list = deleteElement(ra,target); //list = newThing 
list[0], list[1], ... 

그래서 방법의 외부에서 배열의 요소에 액세스하기 위해, 당신은 당신의 클래스/메소드 뭔가에 반환되는 배열을 할당해야하고 그 변수를 운영하고 있습니다.

0

정말로 묻는 질문은 배열의 하위 배열을 조작하는 방법입니다. 결국, 특정 요소에 액세스하는 방법을 알고 있습니다 : a[i] 표기법.

사용할 수있는 대량 메소드 클래스는 Array.copy, Array.copyOfRangeSystem.arrayCopy입니다. 그러나 이러한 방법을 사용하더라도 배열에서 몇 가지 항목을 삭제해야하는 경우 작업을 너무 많이하고 있습니다. 당신이 일을하는 방식은 O (N^2) 작업 일 수 있습니다. 대신 목록을 사용하십시오.

public static Integer[] deleteElement(int[] array, int valueToDelete){ 
    List<Integer> list = new ArrayList<>(); 
    for (int n: array) { 
     if (n != valueToDelete) { 
      list.add(n); 
     } 
    } 
    return Arrays.toArray(new int[0]); 
} 

심지어 문제가 있습니다. 처음에는 어떤 유형의 List을 사용해야하며, 중간에 삭제할 것이므로 LinkedList을 원할 것입니다.

public static <T> void deleteValue(List<T> list, T value) { 
    for (Iterator<T>it = list.iterator(); it.hasNext();) { 
     if (value.equals(it.next()) { 
      it.delete(); 
     } 
    } 
} 
관련 문제