Java中的数组数组

Bru*_*oon 14 php java jsp tomcat

这对我来说是个讨厌的...我是一个在Java项目中使用Java工作的PHP人.我知道如何做我正在尝试通过太多的代码和完全缺乏技巧.

我宁愿做得对.情况如下:

我正在写一个小型显示器,向顾客展示他们根据浇水组(ABCDE)和一年中的什么时间浇灌草坪的日子.我们的季节如下:夏季(5-1至8-31)春季(3-1至4-30)秋季(9-1至10-31)冬季(11-1至2-28)

一个例子可能是:

如果我在A组,这将是我允许的时间:冬天:星期一只有春天:星期二,星期四,星期六夏天:任何一天秋天:星期二,星期四,星期六

如果我用PHP写这个,我会使用这样的数组:

//M=Monday,t=Tuesday,T=Thursday.... etc
$schedule["A"]["Winter"]='M';
$schedule["A"]["Spring"]='tTS';
$schedule["A"]["Summer"]='Any';
$schedule["A"]["Fall"]='tTS';
$schedule["B"]["Winter"]='t';
Run Code Online (Sandbox Code Playgroud)

我可以制作天数组(数组("星期二","星期四","星期六"))等,但这并不是我真正想要完成的事情.

我还需要设置数组以确定我在哪个季节:

$seasons["Summer"]["start"]=0501;
$seasons["Summer"]["end"]=0801;
Run Code Online (Sandbox Code Playgroud)

任何人都可以提出一个非常酷的方法吗?我将有今天的日期和团体信.我需要在一天(M)或一系列日子(tTS),(任何)中退出我的职能.

Mik*_*one 9

您可以使用Hashtables(或其他一些Map)执行基本相同的代码:

Hashtable<String, Hashtable<String, String>> schedule
    = new Hashtable<String, Hashtable<String, String>>();
schedule.put("A", new Hashtable<String, String>());
schedule.put("B", new Hashtable<String, String>());
schedule.put("C", new Hashtable<String, String>());
schedule.put("D", new Hashtable<String, String>());
schedule.put("E", new Hashtable<String, String>());

schedule.get("A").put("Winter", "M");
schedule.get("A").put("Spring", "tTS");
// Etc...
Run Code Online (Sandbox Code Playgroud)

不那么优雅,但是再一次,Java不是一种动态语言,它在语言层面上没有哈希.

注意:您可以做一个更好的解决方案,这只是在我阅读您的问题时突然出现在我脑海中.

  • 使用HashMap而不是Hashtable可以获得更好的性能.像Vector一样,Hashtable非常老,不应该出于性能原因而使用.主要是因为一切都是同步的,什么时候不应该. (4认同)

Vin*_*ert 9

不要试图像PHP一样动态.您可以尝试首先定义您需要的内容.

interface Season
{
    public string getDays();
}

interface User
{
    public Season getWinter();
    public Season getSpring();
    public Season getSummer();
    public Season getFall();
}

interface UserMap
{
    public User getUser(string name);
}
Run Code Online (Sandbox Code Playgroud)

请在使用之前阅读Hashtable的文档.这个类是同步的,这意味着每个调用都受到多线程保护,当你不需要额外的保护时,它会真正减慢访问速度.请使用任何Map实现,例如HashMap或TreeMap.


小智 6

似乎每个人都试图找到Java的方式,就像你在PHP中一样,而不是像在Java中那样.只需将数组的每个部分视为一个对象,或者至少将数组的第一级作为对象,每个子级作为对象内的变量.构建一个数据结构,使用所述对象填充该数据结构,并通过数据结构的给定访问器访问对象.

就像是:

class Schedule
{
  private String group;
  private String season;
  private String rundays;
  public Schedule() { this.group = null; this.season = null; this.rundays= null; }
  public void setGroup(String g) { this.group = g; }
  public String getGroup() { return this.group; }
  ...
}

public ArrayList<Schedule> schedules = new ArrayList<Schedule>();
Schedule s = new Schedule();
s.setGroup(...);
...
schedules.add(s);
...
Run Code Online (Sandbox Code Playgroud)

当然,这可能也不对.我会把每个季节都作为一个对象,也许每个工作日列表都是一个对象.无论如何,它比试图模仿PHP代码的混乱Hashtable更容易重用,理解和扩展.当然,PHP也有对象,你应该尽可能以类似的方式使用它们而不是你的超级数组.不过,我确实理解作弊的诱惑.PHP让它变得如此简单,如此有趣!