首页 \ 问答 \ Java中的泛型类型和对象[复制](Generic Types and Object in Java [duplicate])

Java中的泛型类型和对象[复制](Generic Types and Object in Java [duplicate])

这个问题在这里已经有了答案:

我刚刚已经了解到Java中的泛型类型存在问题。 如果我想编写一个使用泛型类的方法,就会出现问题。 有了明确的类型说明,我将失去泛型类为我提供的灵活性。 我也不能使用“Object”作为Method中的通用数据类型。 但为什么不呢? “对象”是Java中每个类的基本类,并且这种语言具有多态性,所以为什么这不起作用?

自己的例子来演示:

Triplet.java

public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<Object> triplet) {
        System.out.println(triplet.a);
        System.out.println(triplet.b);
        System.out.println(triplet.c);
    }
}

错误信息

Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
        printPartsOfTriplet(triplet);
                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

I just have learned that there is a problem with generic types in Java. The problem occurs if I want to write a method that uses a generic class. With the explicit specification of a type I will lose the flexibility that generic classes offer to me. I also cant use "Object" for the generic data type in the Method. But why not? "Object" is the basic class of every class in Java and this language has polymorphism so why this doesnt work?

Own Example to demonstrate:

Triplet.java

public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<Object> triplet) {
        System.out.println(triplet.a);
        System.out.println(triplet.b);
        System.out.println(triplet.c);
    }
}

Error Message

Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
        printPartsOfTriplet(triplet);
                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

原文:https://stackoverflow.com/questions/47335486
更新时间:2023-01-18 20:01

最满意答案

如果我正确阅读,你只是想

(delete join onto orders)...->groupBy('users.id')->get();

这将返回一个符合条件的用户。

您可以通过2个查询实现此目的,首先按用户分组(不加入订单),然后对订单执行第二次查询。 要加入的其他内容取决于您使用哪些表来过滤用户,以及您使用哪些表向订单添加数据。 将数据添加到第二个查询中的订单,填充您的用户以过滤第一个中的用户。 您也可以尝试使用子查询,但在eloquent中不支持。

此外,您的whereIn完全没有意义,因为您已经在测试用户状态为2或3的位置。

编辑得更清晰,我有点仓促。 原本以为海报想要一排回来 - 事​​实并非如此。


If im reading this right, you just want to

(delete join onto orders)...->groupBy('users.id')->get();

That will return you one user matching the conditions.

You can achieve this with 2 queries, first group by on users (don't join orders), then do a second query for the orders. What else to join would depend on which tables you are using to filter users by vs which tables you are using to add data to orders with. Put data to add to orders in the second query, stuff your using to filter users in the first. You could also try a subquery but that isn't supported well in eloquent.

Also your whereIn is completely pointless, as you are already testing for where user status is 2 or 3.

Edited for a little more clarity,I was a little hasty. Originally thought that the poster wanted one row back - which wasn't the case.

相关问答

更多
  • 尝试: Testimonial::with('area')->get(); try: Testimonial::with('area')->get();
  • 对问题1的回答: 在你的情况下使用eloquent orm时可以使用advance where子句,使用可以尝试: Foo::whereHas('fooTypes', function($query){ $query->whereTypeId(5); })->get(); 对问题2的回答: “数据映射器”或“查询”构建器比ORM活动记录更快。 因此,当您编写具有大量并发请求的非常大的应用程序时,Data Mapper / Query Builder就是您的选择。 另一方面,ORM为刚开始使 ...
  • 你的邮政模特.. namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { public function users() { return $this->belongsTo('App\User', 'author'); } } 现在用它作为...... Post::find(1)->users; 由于帖子只有一个创建者,您可以将Post模型上的users方 ...
  • 您还没有实际执行过查询。 添加get(),all()或first() 此外,您实际上不会返回一个雄辩的模型,因此无法使用雄辩的关系。 您只需添加流畅的查询即可。 尝试这个: $items = Item::join('users AS u', 'i.user_id', '=', 'u.id') ->where('account_id', '=', 5) ->all(); foreach($items as $item){ $imag ...
  • 刚刚将locality_id添加到select中并且工作正常。 实际上雄辩的作品就像你有2个带有相关项目的数组而你想要匹配它们 - 如果其中一个没有外键,那么指向另一个中的主键,则你不能这样做。 Eloquent完全一样。 您必须始终选择关系的两个键(很可能是一个模型上的PK和另一个模型上的FK)。 Just added locality_id to the select and it worked. Actually eloquent works like you have 2 arrays with r ...
  • 如果我正确阅读,你只是想 (delete join onto orders)...->groupBy('users.id')->get(); 这将返回一个符合条件的用户。 您可以通过2个查询实现此目的,首先按用户分组(不加入订单),然后对订单执行第二次查询。 要加入的其他内容取决于您使用哪些表来过滤用户,以及您使用哪些表向订单添加数据。 将数据添加到第二个查询中的订单,填充您的用户以过滤第一个中的用户。 您也可以尝试使用子查询,但在eloquent中不支持。 此外,您的whereIn完全没有意义,因为您已 ...
  • 你可以试试这个。 我假设$ input ['token']是一个有效值。 $user = Token::with('user') ->whereRaw("token_type = ? AND token_value = ?", array('pass_reset', $input['token'])) ->first()->user; You can try this. I assume that $input['token'] is a valid value. $user = Token::wi ...
  • 如果你使用paginate() ,你不需要get() If you use paginate(), you don't need get()
  • 在PDO正在使用的场景背后,这是PDO作为准备好的查询的方式,例如检查: $title = 'Laravel%'; $author = 'John%'; $sql = "SELECT * FROM books WHERE title like ? AND author like ? "; $q = $conn->prepare($sql); $q->execute(array($title,$author)); 在execute()查询期间的运行时间? 标记将被替换为传递的值execute(array(. ...
  • 请尝试以下方法: $workprocess = WPModel::where('work_processes.id', $wpid) ->join('users', 'users.id', '=', 'work_processes.wp_owner_id') ->select('users.user_name', 'work_processes.*') ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)