java 异构数组的意义是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4534612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:48:49  来源:igfitidea点击:

what is the point of heterogenous arrays?

javapythonrubyarraysdynamic

提问by Aaron Yodaiken

I know that more-dynamic-than-Java languages, like Python and Ruby, often allow you to place objects of mixed types in arrays, like so:

我知道比 Java 更动态的语言,例如 Python 和 Ruby,通常允许您将混合类型的对象放在数组中,如下所示:

["hello", 120, ["world"]]

What I don't understand is why you would ever use a feature like this. If I want to store heterogenous data in Java, I'll usually create an object for it.

我不明白的是为什么你会使用这样的功能。如果我想在 Java 中存储异构数据,我通常会为其创建一个对象。

For example, say a Userhas int IDand String name. While I see that in Python/Ruby/PHP you could do something like this:

例如,假设 aUser具有int IDString name。虽然我看到在 Python/Ruby/PHP 中你可以做这样的事情:

[["John Smith", 000], ["Smith John", 001], ...]

this seems a bit less safe/OO than creating a class Userwith attributes IDand nameand then having your array:

这似乎有点不太安全/ OO不是创建一个类User具有属性IDname,然后让你的数组:

[<User: name="John Smith", id=000>, <User: name="Smith John", id=001>, ...]

where those <User ...>things represent User objects.

这些<User ...>东西代表用户对象。

Is there reason to use the former over the latter in languages that support it? Or is there some bigger reason to use heterogenous arrays?

是否有理由在支持它的语言中使用前者而不是后者?或者是否有更大的理由使用异构数组?

N.B. I am not talking about arrays that include different objects that all implement the same interface or inherit from the same parent, e.g.:

注意,我不是在谈论包含不同对象的数组,这些对象都实现了相同的接口或从同一个父级继承,例如:

class Square extends Shape
class Triangle extends Shape
[new Square(), new Triangle()]

because that is, to the programmer at least, still a homogenous array as you'll be doing the same thing with each shape (e.g., calling the draw()method), only the methods commonly defined between the two.

因为那至少对程序员来说仍然是一个同构数组,因为您将对每个形状(例如,调用draw()方法)做同样的事情,只有在两者之间共同定义的方法。

采纳答案by G__

As katrielalex wrote: There is no reason not to support heterogeneous lists. In fact, disallowing it would require static typing, and we're back to that old debate. But let's refrain from doing so and instead answer the "why would you use that" part...

正如 katrielalex 所写:没有理由不支持异构列表。事实上,禁止它需要静态类型,我们又回到了那个古老的争论。但是让我们不要这样做,而是回答“你为什么要使用那个”部分......

To be honest, it is not used thatmuch -- if we make use of the exception in your last paragraph and choose a more liberal definition of "implement the same interface" than e.g. Java or C#. Nearly all of my iterable-crunching code expects all items to implement some interface. Of course it does, otheriwise it could do very little to it!

说实话,它不使用多-如果我们利用例外的在你的最后一段,并选择更自由的定义“实现相同的接口”,比如Java或C#。几乎我所有的可迭代处理代码都希望所有项目都实现某个接口。当然可以,否则它就无能为力了!

Don't get me wrong, there are absolutely valid use cases - there's rarely a good reason to write a whole class for containing some data (and even if you add some callables, functional programming sometimes comes to the rescue). A dict would be a more common choice though, and namedtupleis very neat as well. But they are less common than you seem to think, and they are used with thought and discipline, not for cowboy coding.

不要误会我的意思,有绝对有效的用例 - 很少有充分的理由编写一个完整的类来包含一些数据(即使您添加了一些可调用对象,函数式编程有时也会派上用场)。不过,dict 将是更常见的选择,并且namedtuple也非常简洁。但它们并不像你想象的那么常见,它们被用于思想和纪律,而不是牛仔编码。

(Also, you "Useras nested list" example is not a good one - since the inner lists are fixed-sized, you better use tuples and that makes it valid even in Haskell (type would be [(String, Integer)]))

(另外,你“User作为嵌套列表”的例子不是一个好的例子——因为内部列表是固定大小的,你最好使用元组,这使得它即使在 Haskell 中也有效(类型为[(String, Integer)]))

回答by G__

Applying a multimethodto the array might make some sense. You switch the strategy to a more functional style in which you focus on a discrete piece of logic (i.e. the multimethod) instead of a discrete piece of data (i.e. the array objects).

多方法应用于数组可能有一定的意义。您将策略切换到更实用的风格,在这种风格中,您专注于离散的逻辑(即多方法)而不是离散的数据(即数组对象)。

In your shapes example, this prevents you from having to define and implement the Shapeinterface. (Yes, it's not a big deal here, but what if shape was one of several superclasses you wanted to extend? In Java, you're SOL at this point.) Instead, you implement a smart draw()multimethod that first examines the argument and then dispatches to the proper drawing functionality or error handling if the object isn't drawable.

在您的形状示例中,这可以防止您必须定义和实现Shape接口。(是的,这里没什么大不了的,但是如果 shape 是您想要扩展的几个超类之一呢?在 Java 中,此时您是 SOL。)相反,您实现了一个智能draw()多方法,它首先检查参数,然后如果对象不可绘制,则分派到适当的绘制功能或错误处理。

Comparisons between functional and object-oriented styles are all over the place; here are a couple relevant questions that should provide a good start: Functional programming vs Object Oriented programmingand Explaining functional programming to object-oriented programmers and less technical people.

函数式风格和面向对象风格之间的比较无处不在;这里有几个相关的问题应该提供一个良好的开端:函数式编程 vs 面向对象编程向面向对象的程序员和非技术人员解释函数式编程

回答by Jochen Ritzel

Is there reason to use the former over the latter in languages that support it?

是否有理由在支持它的语言中使用前者而不是后者?

Yes, there is a very simple reason why you can do this in Python (and i assume the same reason in Ruby):

是的,您可以在 Python 中执行此操作有一个非常简单的原因(我假设在 Ruby 中也是如此):

How would you check that a list is heterogenous?

您将如何检查列表是否异质?

  • It can't just compare the types directly because Python has duck typing.
  • If all the object have some common typeclass Python has no way to guess that either. Everythingsupports being represented anyways, so you should be able to put them in a list together too.
  • It wouldn't make any sense to turn lists into the onlytype that needs a type declaration either.
  • 它不能直接比较类型,因为 Python 有鸭子类型。
  • 如果所有对象都有一些通用的类型类,Python 也无法猜测。无论如何,一切都支持repr发送,因此您也应该能够将它们一起放在一个列表中。
  • 将列表变成唯一需要类型声明的类型也没有任何意义。

There is simply no way to prevent you from creating a heterogenous list!

根本没有办法阻止您创建异构列表!

Or is there some bigger reason to use heterogenous arrays?

或者是否有更大的理由使用异构数组?

No, I can't think of any. As you already mentioned in your question, if you use a heterogenous arrays you're just making things harder than they have to be.

不,我想不出任何。正如您在问题中已经提到的,如果您使用异构数组,那么您只会使事情变得比它们必须的更难。

回答by Katriel

There is no reason not to support heterogeneous lists. It's a limitation for technical reasons, and we don't like those.

没有理由不支持异构列表。这是出于技术原因的限制,我们不喜欢这些。

Not everything needs to be a class!

不是所有的东西都需要一个类!

In Python, a class is basically a souped up dictionary with some extra stuff anyway. So making a class Useris not necessarily any clearer than a dictionary {"name": ..., "id": ...}.

在 Python 中,类基本上是一个带有一些额外内容的增强型字典。因此,创建一个类User并不一定比字典更清晰{"name": ..., "id": ...}

回答by Peter Lawrey

There is nothing to stop you having a heterogeneous array in Java. It is considered poor programming style and using proper POJOs will be faster/more efficient than heterogeneous arrays in Java or any other language as the types of the "fields" are statically known and primitives can be used.

没有什么可以阻止您在 Java 中使用异构数组。它被认为是糟糕的编程风格,并且使用适当的 POJO 将比 Java 或任何其他语言中的异构数组更快/更有效,因为“字段”的类型是静态已知的并且可以使用原语。

In Java you can

在 Java 中,您可以

Object[][] array = {{"John Smith", 000}, {"Smith John", 001}, ...};

回答by pythonFoo

Eterogenous lists are very useful. For instance, to make the game of snake, I can have a list of blocks like this: [[x, y, 'down'], [x1, y1, 'down']] instead of a class for the blocks, and I can access faster to every element.

异类列表非常有用。例如,为了制作蛇游戏,我可以有一个这样的块列表:[[x, y, 'down'], [x1, y1, 'down']] 而不是块的类,和我可以更快地访问每个元素。

回答by Gianluca Ghettini

In Lua an object and an array are the same thing so the reason is more clear. Let's say that Lua takes the weak typing to the extreme

在 Lua 中,对象和数组是同一个东西,所以原因更清楚。假设 Lua 将弱类型发挥到了极致

Apart from that, I had a Google Map object and I needed to delete all markers created so far in that map. So I ended up creating an array for markers, an array for circlesand an array for places. Then I made a function to iterate over those three arrays and call .remove()on each of them. I then realized that I could just have a single non homogeneous array and insert into them all the objects and iterate once over that array

除此之外,我有一个 Google Map 对象,我需要删除迄今为止在该地图中创建的所有标记。所以我最终创建了一个数组 for markers,一个数组 forcircles和一个数组 for places。然后我创建了一个函数来迭代这三个数组并调用.remove()它们中的每一个。然后我意识到我可以只有一个非同构数组并将所有对象插入它们并在该数组上迭代一次

回答by xss

Here is a simple answer:

这是一个简单的答案:

N.B. I am not talking about arrays that include different objects that all implement the same interface or inherit from the same parent, e.g.:

注意,我不是在谈论包含不同对象的数组,这些对象都实现了相同的接口或从同一个父级继承,例如:

Everything extends java.lang.Object... and that's plenty. There is no reason notto have Object[] and put anything you like in. Object[] are exceptionally useful in any middleware like persistence layer.

一切都扩展了 java.lang.Object...,这就足够了。没有理由使用 Object[] 并放入您喜欢的任何内容。 Object[] 在任何中间件(如持久层)中都非常有用。