将数组作为对象问题的参数传递

时间:2019-12-23 21:16:10

标签: java arrays object parameters

我想将数组作为对象的参数传递,但是我有点堆栈。 所以这是我的问题。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment  } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class GeolocationService {
  databaseUrl = environment.firebase.databaseURL;

  constructor(private http: HttpClient) {
    console.log('Hello OrganizationService Provider');
    console.log('OrganizationService: ', this.databaseUrl);
  }

  insertUserGeolocation(data) {
    return this.http.post(`${this.databaseUrl}/geolocations.json`, data);
  }
}

4 个答案:

答案 0 :(得分:2)

teachers[1]是数组中的第二个元素。数组本身就是teachers。就像

Publisher2 p1 = new Publisher2(teachers, 20);

答案 1 :(得分:0)

可能您想要执行以下操作:

public class Publisher {

    public static void main(String args[]) {
        String teachers[] = { "Jyothi", "Jyostna", "Sumathi" };
        Publisher2 p1 = new Publisher2(teachers[1], 20);
        System.out.println(p1);
    }
}

class Publisher2 {
    String teacher;
    int y;

    public Publisher2(String teacher, int y) {
        this.teacher = teacher;
        this.y = y;
    }

    @Override
    public String toString() {
        return "Publisher2{" + "teacher=" + teacher + ", y=" + y + '}';
    }
}

输出:

Publisher2{teacher=Jyostna, y=20}

答案 2 :(得分:0)

另一种可能性是使用varargs并交换参数(该varargs必须是参数列表中的最后一个):

λ> combos 1 2
[[1]] -- CORRECT
λ> combos 4 2
[[1,4],[4]] -- WRONG
λ> combos 5 2
[[1,4]] -- CORRECT
λ> combos 10 2
[] -- this should be [[1,9]] -- WRONG
λ> combos 100 2
[[1,4,9,16,25,36,49,64,81,100],[1,4,9,16,25,36,49,64,100],.....] -- WRONG
λ> combos 100 3
[[1,8,27,64]] -- CORRECT

通过这种方法,您可以传递尽可能多的参数(无,单个,多个或数组):

public Publisher2(int y, String... teachers) {
  this.teachers = teachers;                   
  this.y = y;                                 
}                                             

对于new Publisher2(20); new Publisher2(20, teachers[0]); new Publisher2(20, teachers); 问题,您可以使用toString,这样java.util.Arrays看起来像这样:

toString

然后,字符串将看起来像

@Override                                                                           
public String toString() {                                                          
  return "Publisher2{" + "teachers=" + Arrays.toString(teachers) + ", y=" + y + "}";
}                                                                                   

答案 3 :(得分:0)

由于您已在各种注释中阐明了您的问题(请编辑您的问题),所以我们现在知道您要传递单个项目,但是您在代码和注释中隐含了{{1 }}必须以数组作为参数来构造。

因此,您将需要构建一个包含单个项目的新数组。

Publisher2

或...

String[] teacherSubset = new String[] { teachers[1] };
Publisher2 p1 = new Publisher2(teacherSubset, 20);

请修改您的问题,以使您清楚地知道要完成的任务。