Корректный способ инициализировать HashMap и HashMap может содержать различные типы значения?

Я использую fin-hypergrid 3.2.0 версия . Здесь этот ответ покажет, как использовать его внутри углового 2+.

import { Component, OnInit, AfterViewInit } from '@angular/core';
import * as Hypergrid from 'fin-hypergrid';

@Component({
  selector: 'app-markbook-new',
  templateUrl: './markbook-new.page.html',
  styleUrls: ['./markbook-new.page.scss']
})
export class MarkBookNewPage implements OnInit, AfterViewInit {
  protected grid: Hypergrid;

  constructor() {
    const data = [
        {
            "Name": "Alabama",
            "Code": "AL",
            "Capital": "Montgomery",
            "Statehood": "December 14, 1819",
            "Population": 4833722,
            "Area": 52420,
            "House Seats": 7
        }
    ];
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
     this.grid = new Hypergrid('#' + 'json-example',
            {
              data: this._rowList,
              schema: [],
              canvasContextAttributes: { alpha: true }
            });
  }

  async ionViewDidEnter() {

  }

}

И вам не нужно schema: [], canvasContextAttributes: { alpha: true }, это решит вашу проблему. Но вам нужно больше работать над тем, чтобы заставить работать сетку.

63
задан jbatista 29 September 2011 в 12:33
поделиться

8 ответов

It really depends on what kind of type safety you need. The non-generic way of doing it is best done as:

 Map x = new HashMap();

Note that x is typed as a Map. this makes it much easier to change implementations (to a TreeMap or a LinkedHashMap) in the future.

You can use generics to ensure a certain level of type safety:

Map<String, Object> x = new HashMap<String, Object>();

In Java 7 and later you can do

Map<String, Object> x = new HashMap<>();

The above, while more verbose, avoids compiler warnings. In this case the content of the HashMap can be any Object, so that can be Integer, int[], etc. which is what you are doing.

If you are still using Java 6, Guava Libraries (although it is easy enough to do yourself) has a method called newHashMap() which avoids the need to duplicate the generic typing information when you do a new. It infers the type from the variable declaration (this is a Java feature not available on constructors prior to Java 7).

By the way, when you add an int or other primitive, Java is autoboxing it. That means that the code is equivalent to:

 x.put("one", Integer.valueOf(1));

You can certainly put a HashMap as a value in another HashMap, but I think there are issues if you do it recursively (that is put the HashMap as a value in itself).

102
ответ дан 24 November 2019 в 16:18
поделиться

Map.of литералы

С Java 9, существует еще один способ инстанцировать Map. Можно создать немодифицируемую карту из нуля, один, или несколько пар объектов в одной строке кода. Это довольно удобно во многих ситуациях.

Для пустого Map, который не может быть изменен, звоните Map.of() . Почему Вы хотели бы пустое множество, которое не может быть изменено? Один общий падеж должен постараться не возвращать ПУСТОЙ УКАЗАТЕЛЬ, где у Вас нет допустимого содержания.

Для единственной пары "ключ-значение", звоните Map.of( myKey , myValue ) . Например, Map.of( "favorite_color" , "purple" ).

Для нескольких пар "ключ-значение", используйте серию пар "ключ-значение". ''Map.of ("favorite_foreground_color", "фиолетовый", "favorite_background_color", "сливки")'.

, Если тех пар трудно считать, можно хотеть использовать Map.of и передача Map.Entry объекты.

Примечание, что мы возвращаем объект эти Map интерфейс. Мы не знаем, что базовый реальный класс раньше делал наш объект. Действительно, команда Java свободна к используемым различным реальным классам для различных данных, или варьироваться класс по будущим выпускам Java.

правила, обсужденные в других Ответах все еще, применяются здесь относительно безопасности типов. Вы объявляете свои намеченные типы, и должны соответствовать Ваши переданные объекты. Если Вы хотите значения различных типов, используйте Object .

Map< String , Color > preferences = Map.of( "favorite_color" , Color.BLUE ) ;
0
ответ дан 24 November 2019 в 16:18
поделиться

This is a change made with Java 1.5. What you list first is the old way, the second is the new way.

By using HashMap you can do things like:

HashMap<String, Doohickey> ourMap = new HashMap<String, Doohickey>();

....

Doohickey result = ourMap.get("bob");

If you didn't have the types on the map, you'd have to do this:

Doohickey result = (Doohickey) ourMap.get("bob");

It's really very useful. It helps you catch bugs and avoid writing all sorts of extra casts. It was one of my favorite features of 1.5 (and newer).

You can still put multiple things in the map, just specify it as Map, then you can put any object in (a String, another Map, and Integer, and three MyObjects if you are so inclined).

14
ответ дан 24 November 2019 в 16:18
поделиться

Eclipse рекомендует объявить тип HashMap, потому что это обеспечивает некоторую безопасность типов. Конечно, похоже, что вы пытаетесь избежать безопасности типов во второй части.

Если вы хотите сделать последнее, попробуйте объявить карту как HashMap .

4
ответ дан 24 November 2019 в 16:18
поделиться

То, как вы это пишете, эквивалентно

HashMap<Object, Object> map = new HashMap<Object, Object>();

. В скобках заключено то, что вы сообщаете компилятору, что вы собираетесь поместить в HashMap, чтобы он мог делать ошибку. проверяю для вас. Если Object, Object - это то, что вы действительно хотите (возможно, нет), вы должны явно объявить это. В общем, вы должны быть как можно более точными в объявлении, чтобы облегчить проверку ошибок компилятором. То, что вы описали, вероятно, следует объявить следующим образом:

HashMap<String, Object> map = new HashMap<String, Object>();

Таким образом вы, по крайней мере, объявите, что ваши ключи будут строками, но ваши значения могут быть любыми. Просто не забудьте использовать приведение, когда вы получите значение обратно.

3
ответ дан 24 November 2019 в 16:18
поделиться

The 2nd one is using generics which came in with Java 1.5. It will reduce the number of casts in your code & can help you catch errors at compiletime instead of runtime. That said, it depends on what you are coding. A quick & dirty map to hold a few objects of various types doesn't need generics. But if the map is holding objects all descending from a type other than Object, it can be worth it.

The prior poster is incorrect about the array in a map. An array is actually an object, so it is a valid value.

Map<String,Object> map = new HashMap<String,Object>();
map.put("one",1); // autoboxed to an object
map.put("two", new int[]{1,2} ); // array of ints is an object
map.put("three","hello"); // string is an object

Also, since HashMap is an object, it can also be a value in a HashMap.

2
ответ дан 24 November 2019 в 16:18
поделиться

In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.

That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap

0
ответ дан 24 November 2019 в 16:18
поделиться

A HashMap can hold any object as a value, even if it is another HashMap. Eclipse is suggesting that you declare the types because that is the recommended practice for Collections. under Java 5. You are free to ignore Eclipse's suggestions.

Under Java 5, an int (or any primitive type) will be autoboxed into an Integer (or other corresponding type) when you add it to a collection. Be careful with this though, as there are some catches to using autoboxing.

1
ответ дан 24 November 2019 в 16:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: